public AdData() { Mq = BlockingMq.GetMq(); // figure out domain context if (MyOptions.TargetDomain == null && MyOptions.TargetDc == null) { try { DirectoryContext = new DirectoryContext(DirectoryContextType.Domain, Domain.GetCurrentDomain().Name); } catch (Exception e) { Mq.Error( "Problem figuring out DirectoryContext, you might need to define manually with -d and/or -c."); Mq.Degub(e.ToString()); Mq.Terminate(); } } else if (!String.IsNullOrEmpty(MyOptions.TargetDc)) { DirectoryContext = new DirectoryContext(DirectoryContextType.Domain, MyOptions.TargetDc); } else if (!String.IsNullOrEmpty(MyOptions.TargetDomain)) { DirectoryContext = new DirectoryContext(DirectoryContextType.Domain, MyOptions.TargetDomain); } SetDomainUsersAndComputers(); }
private string GetShareName(HostShareInfo hostShareInfo, string computer) { // takes a HostShareInfo object and a computer name and turns it into a usable path. // first we want to throw away any errored out ones. string[] errors = { "ERROR=53", "ERROR=5" }; if (errors.Contains(hostShareInfo.shi1_netname)) { //Mq.Trace(hostShareInfo.shi1_netname + " on " + computer + //", but this is usually no cause for alarm."); return(null); } Mq.Degub("Share discovered: " + $"\\\\{computer}\\{hostShareInfo.shi1_netname}"); return($"\\\\{computer}\\{hostShareInfo.shi1_netname}"); }
private void GetDomainControllers() { try { DomainControllerCollection dcCollection = DomainController.FindAll(DirectoryContext); foreach (DomainController dc in dcCollection) { DomainControllers.Add(dc.IPAddress); } } catch (Exception e) { Mq.Error( "Something went wrong trying to find domain controllers. Try defining manually with -c?"); Mq.Degub(e.ToString()); Mq.Terminate(); } }
private void ParseLogLevelString(string logLevelString) { switch (logLevelString.ToLower()) { case "debug": LogLevel = LogLevel.Debug; Mq.Degub("Set verbosity level to degub."); break; case "degub": LogLevel = LogLevel.Debug; Mq.Degub("Set verbosity level to degub."); break; case "trace": LogLevel = LogLevel.Trace; Mq.Degub("Set verbosity level to trace."); break; case "data": LogLevel = LogLevel.Warn; Mq.Degub("Set verbosity level to data."); break; case "info": LogLevel = LogLevel.Info; Mq.Degub("Set verbosity level to info."); break; default: LogLevel = LogLevel.Info; Mq.Error("Invalid verbosity level " + logLevelString + " falling back to default level (info)."); break; } }
public void WalkTree(string currentDir) { // Walks a tree checking files and generating results as it goes. if (!Directory.Exists(currentDir)) { return; } try { string[] files = Directory.GetFiles(currentDir); // check if we actually like the files foreach (string file in files) { FileTaskScheduler.New(() => { try { FileScanner.ScanFile(file); } catch (Exception e) { Mq.Error("Exception in FileScanner task for file " + file); Mq.Trace(e.ToString()); } }); } } catch (UnauthorizedAccessException) { //Mq.Trace(e.ToString()); //continue; } catch (DirectoryNotFoundException) { //Mq.Trace(e.ToString()); //continue; } catch (IOException) { //Mq.Trace(e.ToString()); //continue; } catch (Exception e) { Mq.Degub(e.ToString()); //continue; } try { string[] subDirs = Directory.GetDirectories(currentDir); // Create a new treewalker task for each subdir. if (subDirs.Length >= 1) { foreach (string dirStr in subDirs) { bool scanDir = true; foreach (ClassifierRule classifier in MyOptions.DirClassifiers) { try { DirClassifier dirClassifier = new DirClassifier(classifier); DirResult dirResult = dirClassifier.ClassifyDir(dirStr); if (dirResult.ScanDir == false) { scanDir = false; break; } } catch (Exception e) { Mq.Trace(e.ToString()); continue; } } if (scanDir == true) { TreeTaskScheduler.New(() => { try { WalkTree(dirStr); } catch (Exception e) { Mq.Error("Exception in TreeWalker task for dir " + dirStr); Mq.Error(e.ToString()); } }); } else { Mq.Trace("Skipped scanning on " + dirStr + " due to Discard rule match."); } } } } catch (UnauthorizedAccessException) { //Mq.Trace(e.ToString()); //continue; } catch (DirectoryNotFoundException) { //Mq.Trace(e.ToString()); //continue; } catch (IOException) { //Mq.Trace(e.ToString()); //continue; } catch (Exception e) { Mq.Trace(e.ToString()); //continue; } }
internal void GetComputerShares(string computer) { // find the shares HostShareInfo[] hostShareInfos = GetHostShareInfo(computer); foreach (HostShareInfo hostShareInfo in hostShareInfos) { // skip IPC$ and PRINT$ shares for #OPSEC!!! List <string> neverScan = new List <string> { "ipc$", "print$" }; if (neverScan.Contains(hostShareInfo.shi1_netname.ToLower())) { continue; } string shareName = GetShareName(hostShareInfo, computer); if (!String.IsNullOrWhiteSpace(shareName)) { bool matched = false; // SYSVOL and NETLOGON shares are replicated so they have special logic - do not use Classifiers for these switch (hostShareInfo.shi1_netname.ToUpper()) { case "SYSVOL": if (MyOptions.ScanSysvol == true) { // Leave matched as false so that we don't suppress the TreeWalk for the first SYSVOL replica we see. // Toggle the flag so that any other shares replica will be skipped MyOptions.ScanSysvol = false; break; } matched = true; break; case "NETLOGON": if (MyOptions.ScanNetlogon == true) { // Same logic as SYSVOL above MyOptions.ScanNetlogon = false; break; } matched = true; break; default: // classify them foreach (ClassifierRule classifier in MyOptions.ShareClassifiers) { ShareClassifier shareClassifier = new ShareClassifier(classifier); if (shareClassifier.ClassifyShare(shareName)) { // in this instance 'matched' means 'matched a discard rule, so don't send to treewalker'. matched = true; break; } } break; } // by default all shares should go on to TreeWalker unless the classifier pulls them out. // send them to TreeWalker if (!matched) { // At least one classifier was matched so we will return this share to the results ShareResult shareResult = new ShareResult() { Listable = true, SharePath = shareName, ShareComment = hostShareInfo.shi1_remark.ToString() }; // Try to find this computer+share in the list of DFS targets /* * foreach (DFSShare dfsShare in MyOptions.DfsShares) * { * ///TODO: Add some logic to match cases where short hostnames is used in DFS target list * if (dfsShare.RemoteServerName.Equals(computer, StringComparison.OrdinalIgnoreCase) && * dfsShare.Name.Equals(hostShareInfo.shi1_netname, StringComparison.OrdinalIgnoreCase)) * { * // why the not operator? if (!MyOptions.DfsNamespacePaths.Contains(dfsShare.DfsNamespacePath)) * if (MyOptions.DfsNamespacePaths.Contains(dfsShare.DfsNamespacePath)) * { * // remove the namespace path to make sure we don't kick it off again. * MyOptions.DfsNamespacePaths.Remove(dfsShare.DfsNamespacePath); * // sub out the \\computer\share path for the dfs namespace path. this makes sure we hit the most efficient endpoint. * shareName = dfsShare.DfsNamespacePath; * } * else // if that dfs namespace has already been removed from our list, skip further scanning of that share. * { * skip = true; * } * * // Found DFS target matching this computer+share - no further comparisons needed * break; * } * } */ // If this path can be accessed via DFS if (MyOptions.DfsSharesDict.ContainsKey(shareName)) { string dfsUncPath = MyOptions.DfsSharesDict[shareName]; Mq.Degub(String.Format("Matched host path {0} to DFS {1}", shareName, dfsUncPath)); // and if we haven't already scanned this share if (MyOptions.DfsNamespacePaths.Contains(dfsUncPath)) { Mq.Degub(String.Format("Will scan {0} using DFS referral instead of explicit host", dfsUncPath)); // sub out the \\computer\share path for the dfs namespace path. this makes sure we hit the most efficient endpoint. shareResult.SharePath = dfsUncPath; // remove the namespace path to make sure we don't kick it off again. MyOptions.DfsNamespacePaths.Remove(dfsUncPath); } else // if that dfs path has already been removed from our list, skip further scanning of that share. { // Do we want to report a gray share result for these? I think not. // Mq.ShareResult(shareResult); break; } } // If the share is readable then dig deeper. if (IsShareReadable(shareResult.SharePath)) { // Share is readable, report as green (the old default/min of the Triage enum ) shareResult.Triage = Triage.Green; try { DirectoryInfo dirInfo = new DirectoryInfo(shareResult.SharePath); //EffectivePermissions.RwStatus rwStatus = effectivePermissions.CanRw(dirInfo); shareResult.RootModifyable = false; shareResult.RootWritable = false; shareResult.RootReadable = true; /* * if (rwStatus.CanWrite || rwStatus.CanModify) * { * triage = Triage.Yellow; * } */ } catch (System.UnauthorizedAccessException e) { Mq.Error("Failed to get permissions on " + shareResult.SharePath); } if (MyOptions.ScanFoundShares) { Mq.Trace("Creating a TreeWalker task for " + shareResult.SharePath); TreeTaskScheduler.New(() => { try { TreeWalker.WalkTree(shareResult.SharePath); } catch (Exception e) { Mq.Error("Exception in TreeWalker task for share " + shareResult.SharePath); Mq.Error(e.ToString()); } }); } Mq.ShareResult(shareResult); } else if (MyOptions.LogDeniedShares == true) { Mq.ShareResult(shareResult); } } } } }
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()); } }
public bool Parse(string[] args) { Mq.Info("Parsing args..."); var success = false; // define args var outFileArg = new ValueArgument <string>('o', "outfile", "Path for output file. You probably want this if you're not using -s."); var verboseArg = new ValueArgument <string>('v', "verbosity", "Controls verbosity level, options are Trace (most verbose), Debug (less verbose), Info (less verbose still, default), and Data (results only). e.g '-v debug' "); var helpArg = new SwitchArgument('h', "help", "Displays this help.", false); //var extMatchArg = new ValueArgument<string>('e', "extmatch", // "Path to wordlist for searching by exact extension match."); //var nameMatchArg = new ValueArgument<string>('n', "namematch", // "Path to wordlist for searching by exact filename match."); //var grepMatchArg = new ValueArgument<string>('g', "grepmatch", // "Path to wordlist for searching by grepping the contents of files with \"interesting\" extensions."); //var partialMatchArg = new ValueArgument<string>('p', "partialmatch", // "Path to wordlist for searching by partial filename match."); //var pathMatchArg = new ValueArgument<string>('a', "pathmatch", // "Path to wordlist for searching by partial path match."); //var extSkipMatchArg = new ValueArgument<string>('x', "extskipmatch", // "Path to wordlist for extensions that should be skipped."); var stdOutArg = new SwitchArgument('s', "stdout", "Enables outputting results to stdout as soon as they're found. You probably want this if you're not using -o.", false); var mirrorArg = new ValueArgument <string>('m', "mirror", "Enables and assigns an output dir for snaffler to automatically take a copy of any found files."); var fileHuntArg = new SwitchArgument('f', "filehuntoff", "Disables file discovery, will only perform computer and share discovery.", false); var dirTargetArg = new ValueArgument <string>('i', "dirtarget", "Disables computer and share discovery, requires a path to a directory in which to perform file discovery."); var maxThreadsArg = new ValueArgument <int>('t', "threads", "Maximum number of threads. Default 30."); var domainArg = new ValueArgument <string>('d', "domain", "Domain to search for computers to search for shares on to search for files in. Easy."); var adminshareArg = new SwitchArgument('a', "cdolla", "Enables scanning of C$ shares if found. Can be prone to false positives but more thorough.", false); var domainControllerArg = new ValueArgument <string>('c', "domaincontroller", "Domain controller to query for a list of domain computers."); var maxGrepSizeArg = new ValueArgument <long>('r', "maxgrepsize", "The maximum size file (in bytes) to search inside for interesting strings. Defaults to 500k."); var grepContextArg = new ValueArgument <int>('j', "grepcontext", "How many bytes of context either side of found strings in files to show, e.g. -j 200"); // list of letters i haven't used yet: bklquwyz var parser = new CommandLineParser.CommandLineParser(); parser.Arguments.Add(outFileArg); parser.Arguments.Add(helpArg); //parser.Arguments.Add(extMatchArg); //parser.Arguments.Add(nameMatchArg); //parser.Arguments.Add(grepMatchArg); //parser.Arguments.Add(extSkipMatchArg); //parser.Arguments.Add(partialMatchArg); parser.Arguments.Add(stdOutArg); parser.Arguments.Add(mirrorArg); parser.Arguments.Add(fileHuntArg); parser.Arguments.Add(dirTargetArg); parser.Arguments.Add(maxThreadsArg); parser.Arguments.Add(domainArg); parser.Arguments.Add(verboseArg); parser.Arguments.Add(adminshareArg); parser.Arguments.Add(domainControllerArg); parser.Arguments.Add(maxGrepSizeArg); parser.Arguments.Add(grepContextArg); // extra check to handle builtin behaviour from cmd line arg parser if ((args.Contains("--help") || args.Contains("/?") || args.Contains("help") || args.Contains("-h") || args.Length == 0)) { parser.ShowUsage(); Environment.Exit(0); } try { parser.ParseCommandLine(args); // get the args into our config // output args if (outFileArg.Parsed && (outFileArg.Value != null)) { LogToFile = true; LogFilePath = outFileArg.Value; Mq.Degub("Logging to file at " + LogFilePath); } // Set loglevel. if (verboseArg.Parsed) { var logLevelString = verboseArg.Value; switch (logLevelString.ToLower()) { case "debug": LogLevel = LogLevel.Debug; Mq.Degub("Set verbosity level to degub."); break; case "degub": LogLevel = LogLevel.Debug; Mq.Degub("Set verbosity level to degub."); break; case "trace": LogLevel = LogLevel.Trace; Mq.Degub("Set verbosity level to trace."); break; case "data": LogLevel = LogLevel.Warn; Mq.Degub("Set verbosity level to data."); break; default: LogLevel = LogLevel.Info; Mq.Error("Invalid verbosity level " + logLevelString + " falling back to default level (info)."); break; } } // if enabled, display findings to the console LogToConsole = stdOutArg.Parsed; Mq.Degub("Enabled logging to stdout."); if (maxThreadsArg.Parsed) { MaxThreads = maxThreadsArg.Value; Mq.Degub("Max threads set to " + maxThreadsArg.Value); } // args that tell us about targeting if ((domainArg.Parsed) && (domainArg.Value != null)) { TargetDomain = domainArg.Value; Mq.Degub("Target domain is " + domainArg.Value); } if ((domainControllerArg.Parsed) && (domainControllerArg.Value != null)) { TargetDc = domainControllerArg.Value; Mq.Degub("Target DC is " + domainControllerArg.Value); } if (dirTargetArg.Parsed) { ShareFinderEnabled = false; DirTarget = dirTargetArg.Value; Mq.Degub("Disabled finding shares."); Mq.Degub("Target path is " + dirTargetArg.Value); } if (adminshareArg.Parsed) { ScanCDollarShares = true; Mq.Degub("Scanning of C$ shares enabled."); } // if the user passes the various MatchArgs with no value, that disables them. // Otherwise load their wordlist into the appropriate config item. /* * if (extMatchArg.Parsed) * { * if (extMatchArg.Value.Length <= 0) * { * ExactExtensionCheck = false; * Mq.Degub("Disabled matching based on exact file extension match."); * } * else * { * ExtensionsToKeep = File.ReadAllLines(extMatchArg.Value); * Mq.Degub("Using file at " + extMatchArg.Value + " for exact file extension matching."); * } * } * * if (pathMatchArg.Parsed) * { * if (pathMatchArg.Value.Length <= 0) * { * PartialPathCheck = false; * Mq.Degub("Disabled matching based on partial file path."); * } * else * { * PathsToKeep = File.ReadAllLines(pathMatchArg.Value); * Mq.Degub("Using file at " + pathMatchArg.Value + " for partial file path matching."); * } * } * * if (extSkipMatchArg.Parsed) * { * if (extSkipMatchArg.Value.Length <= 0) * { * ExactExtensionSkipCheck = false; * Mq.Degub("Disabled skipping files with extensions on skip-list."); * } * else * { * ExtSkipList = File.ReadAllLines(extSkipMatchArg.Value); * Mq.Degub("Using file at " + extSkipMatchArg.Value + " for extension skip-list."); * } * } * * if (nameMatchArg.Parsed) * { * if (nameMatchArg.Value.Length <= 0) * { * ExactNameCheck = false; * Mq.Degub("Disabled matching based on exact file name"); * } * else * { * FileNamesToKeep = File.ReadAllLines(nameMatchArg.Value); * Mq.Degub("Using file at " + nameMatchArg.Value + " for exact file name matching."); * } * } * * if (grepMatchArg.Parsed) * { * if (grepMatchArg.Value.Length <= 0) * { * GrepByExtensionCheck = false; * Mq.Degub("Disabled matching based on file contents."); * } * else * { * GrepStrings = File.ReadAllLines(grepMatchArg.Value); * Mq.Degub("Using file at " + grepMatchArg.Value + " for file contents matching."); * } * } * * if (partialMatchArg.Parsed) * { * if (partialMatchArg.Value.Length <= 0) * { * PartialNameCheck = false; * Mq.Degub("Disabled partial file name matching."); * } * else * { * NameStringsToKeep = File.ReadAllLines(partialMatchArg.Value); * Mq.Degub("Using file at " + partialMatchArg.Value + " for partial file name matching."); * } * } */ if (maxGrepSizeArg.Parsed) { MaxSizeToGrep = maxGrepSizeArg.Value; Mq.Degub("We won't bother looking inside files if they're bigger than " + MaxSizeToGrep + " bytes"); } // how many bytes if (grepContextArg.Parsed) { GrepContextBytes = grepContextArg.Value; Mq.Degub( "We'll show you " + grepContextArg.Value + " bytes of context around matches inside files."); } // if enabled, grab a copy of files that we like. if (mirrorArg.Parsed) { if (mirrorArg.Value.Length <= 0) { Mq.Error("-m or -mirror arg requires a path value."); throw new ArgumentException("Invalid argument combination."); } EnableMirror = true; MirrorPath = mirrorArg.Value.TrimEnd('\\'); Mq.Degub("Mirroring matched files to path " + MirrorPath); } if (!LogToConsole && !LogToFile) { Mq.Error( "\nYou didn't enable output to file or to the console so you won't see any results or debugs or anything. Your l0ss."); throw new ArgumentException("Pointless argument combination."); } } catch (Exception e) { Mq.Error(e.ToString()); throw; } success = true; return(success); }
public void WalkTree(string currentDir, int delayTime = 1) { // Walks a tree checking files and generating results as it goes. if (!Directory.Exists(currentDir)) { return; } try { string[] files = Directory.GetFiles(currentDir); // check if we actually like the files foreach (string file in files) { //FileTaskScheduler.New(() => //{ try { FileScanner.ScanFile(file); } catch (Exception e) { Mq.Error("Exception in FileScanner task for file " + file); Mq.Trace(e.ToString()); } //Mq.Info("Sleeping " + delayTime.ToString() + " Seconds"); System.Threading.Thread.Sleep(delayTime); //}); } } catch (UnauthorizedAccessException) { //Mq.Trace(e.ToString()); //continue; } catch (DirectoryNotFoundException) { //Mq.Trace(e.ToString()); //continue; } catch (Exception e) { Mq.Trace(e.ToString()); //continue; } try { string[] subDirs = Directory.GetDirectories(currentDir); // Create a new treewalker task for each subdir. if (subDirs.Length >= 1) { foreach (string dirStr in subDirs) { Mq.Degub($"Processing directory {dirStr}"); foreach (ClassifierRule classifier in MyOptions.DirClassifiers) { try { DirClassifier dirClassifier = new DirClassifier(classifier); DirResult dirResult = dirClassifier.ClassifyDir(dirStr); if (dirResult.ScanDir) { //TreeTaskScheduler.New(() => //{ try { WalkTree(dirStr, delayTime); } catch (Exception e) { Mq.Error("Exception in TreeWalker task for dir " + dirStr); Mq.Error(e.ToString()); } //}); } } catch (Exception e) { Mq.Trace(e.ToString()); continue; } // Mq.Info("Sleeping " + delayTime.ToString() + " Seconds"); System.Threading.Thread.Sleep(delayTime); } } } } catch (UnauthorizedAccessException) { //Mq.Trace(e.ToString()); //continue; } catch (DirectoryNotFoundException) { //Mq.Trace(e.ToString()); //continue; } catch (Exception e) { Mq.Trace(e.ToString()); //continue; } }