public bool AuthenticateByUsername(string Username) { PersonLogin domainPersonLogin = null; LDAPConfig objLDAPConfig = new LDAPConfig { IsConfigured = true, IsAuthByPassword = true, LDAPPath = "LDAP://JTINDIA.COM", UserName = "******", Password = "******", ModifiedBy = 1, ModifiedDate = new DateTime() }; string userName = Username; if (!string.IsNullOrWhiteSpace(userName)) { // bool isValidLDAPUser = new LDAPAuthentication(objLDAPConfig.LDAPPath, objLDAPConfig.UserName, Encryption.DecryptText(objLDAPConfig.Password)).AuthenticateWithUserName(userName); bool isValidLDAPUser = new LDAPAuthentication(objLDAPConfig.LDAPPath, objLDAPConfig.UserName, objLDAPConfig.Password).AuthenticateWithUserName(userName); if (isValidLDAPUser) { domainPersonLogin = new PersonLogin { IsLDAPUser = true, Password = "", UserName = "" }; } } return(true); }
/// <summary> /// Init and check defaults /// </summary> /// <param name="context"></param> /// <param name="options"></param> /// <returns></returns> public IContext Initialize(IContext context, LDAPConfig options) { context.Logger.LogTrace("Entering initialize link"); //We've successfully parsed arguments, lets do some options post-processing. var currentTime = DateTime.Now; //var padString = new string('-', initString.Length); context.Logger.LogInformation("Initializing SharpHound at {time} on {date}", currentTime.ToShortTimeString(), currentTime.ToShortDateString()); // Check to make sure both LDAP options are set if either is set if (options.Password != null && options.Username == null || options.Username != null && options.Password == null) { context.Logger.LogTrace("You must specify both LdapUsername and LdapPassword if using these options!"); context.Flags.IsFaulted = true; return(context); } //Check some loop options if (!context.Flags.Loop) { return(context); } //If loop is set, ensure we actually set options properly if (context.LoopDuration == TimeSpan.Zero) { context.Logger.LogTrace("Loop specified without a duration. Defaulting to 2 hours!"); context.LoopDuration = TimeSpan.FromHours(2); } if (context.LoopInterval == TimeSpan.Zero) { context.LoopInterval = TimeSpan.FromSeconds(30); } context.Logger.LogTrace("Exiting initialize link"); return(context); }
public LDAPResponse Connect(UserInfo userInfo, LDAPConfig config) { LdapEntry user; LDAPResponse response = new LDAPResponse(); try { #region Check Parameters if (string.IsNullOrEmpty(config.Url)) { throw new Exception("InvalidLDAPUrlConfigParameter"); } if (string.IsNullOrEmpty(config.BindDn)) { throw new Exception("InvalidLDAPBindDnConfigParameter"); } if (string.IsNullOrEmpty(config.BindCredentials)) { throw new Exception("InvalidLDAPBindCridentialsConfigParameter"); } if (string.IsNullOrEmpty(config.SearchBase)) { throw new Exception("InvalidLDAPSearchFilterConfigParameter"); } if (string.IsNullOrEmpty(config.SearchFilter)) { throw new Exception("InvalidLDAPSearchBaseConfigParameter"); } if (string.IsNullOrEmpty(config.AdminCn)) { throw new Exception("InvalidLDAPAdminCNConfigParameter"); } if (string.IsNullOrEmpty(userInfo.UserName)) { throw new Exception("UserNameMustBeDefined"); } if (string.IsNullOrEmpty(userInfo.Password)) { throw new Exception("PasswordMustBeDefined"); } #endregion var connection = new LdapConnection { SecureSocketLayer = false, ConnectionTimeout = config.ConnectionTimeOut }; connection.Connect(config.Url, LdapConnection.DEFAULT_PORT); connection.Bind(config.BindDn, config.BindCredentials); var searchFilter = string.Format(config.SearchFilter, userInfo.UserName); var result = connection.Search( config.SearchBase, LdapConnection.SCOPE_SUB, searchFilter, new[] { MemberOfAttribute, DisplayNameAttribute, SAMAccountNameAttribute, MailAttribute, MobileAttribute, FirstNameAtribute, LastNameAttribute }, false ); try { user = result.Next(); if (user != null) { connection.Bind(user.DN, userInfo.Password); if (connection.Bound) { response.IsSuccess = true; response.DisplayName = user.getAttribute(DisplayNameAttribute)?.StringValue ?? ""; response.Username = user.getAttribute(SAMAccountNameAttribute)?.StringValue ?? ""; response.Mail = user.getAttribute(MailAttribute)?.StringValue ?? ""; response.Mobile = user.getAttribute(MobileAttribute)?.StringValue ?? ""; response.FirstName = user.getAttribute(FirstNameAtribute)?.StringValue ?? ""; response.LastName = user.getAttribute(LastNameAttribute)?.StringValue ?? ""; response.IsAdmin = false; } else { throw new Exception("LDAPPasswordInCorrect"); } } else { throw new Exception("LDAPUserNotFound"); } } catch (Exception ex) { throw new Exception(ex.Message); } } catch (Exception ex) { response.IsSuccess = false; response.ErrorMessage = ex.Message; } return(response); }
static void Run(CLIOptions opts) { if ((string.IsNullOrEmpty(opts.SprayPassword)) && (opts.Action == LDAPAction.SPRAY_USERS)) { Console.WriteLine("Please supply a password to spray: "); var response = Console.ReadLine(); if (!string.IsNullOrEmpty(response)) { opts.SprayPassword = response; } else { Console.WriteLine($"Missing --spraypassword argument."); Environment.Exit(0); } } if ((string.IsNullOrEmpty(opts.PolicyName)) && (opts.Action == LDAPAction.GET_POLICY_USERS)) { Console.WriteLine("Please supply a policy name: "); var response = Console.ReadLine(); if (!string.IsNullOrEmpty(response)) { opts.PolicyName = response; } else { Console.WriteLine($"Missing --policy argument."); Environment.Exit(0); } } if ((string.IsNullOrEmpty(opts.OutputPath)) && (opts.Quiet)) { Console.WriteLine("Missing --output argument while supplying --quiet, please supply an output directory: "); var response = Console.ReadLine(); if (!string.IsNullOrEmpty(response)) { opts.OutputPath = response; } else { Console.WriteLine($"Missing --output argument while using --quiet."); Environment.Exit(0); } } var config = new LDAPConfig() { DomainName = opts.DomainName, DomainController = opts.DomainController, DomainUsername = opts.DomainUsername, DomainPassword = opts.DomainPassword, SprayPassword = opts.SprayPassword, Auto = opts.Auto, OutputPath = opts.OutputPath, ExcludeFilePath = opts.ExcludeFilePath, SaveOutput = !string.IsNullOrEmpty(opts.OutputPath), ExcludeUsers = !string.IsNullOrEmpty(opts.ExcludeFilePath), Logger = new ConsoleLogger(opts.Quiet) }; switch (opts.Nozzle) { case NozzleType.LDAP: var ldapNozzle = new LDAPNozzle(config); switch (opts.Action) { case LDAPAction.GET_POLICIES: ldapNozzle.DisplayPolicies(); break; case LDAPAction.GET_POLICY_USERS: ldapNozzle.DisplayPolicyUsers(opts.PolicyName, false); break; case LDAPAction.GET_ENABLED_USERS: ldapNozzle.DisplayEnabledUsers(); break; case LDAPAction.SPRAY_USERS: ldapNozzle.Start(); break; } break; } }
/// <summary> /// Init and check defaults /// </summary> /// <param name="context"></param> /// <param name="options"></param> /// <returns></returns> public IContext Initialize(IContext context, LDAPConfig options) { context.Logger.LogTrace("Entering initialize link"); JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Converters = new List <JsonConverter> { new KindConvertor() } }; CommonLib.ReconfigureLogging(context.Logger); //We've successfully parsed arguments, lets do some options post-processing. var currentTime = DateTime.Now; //var padString = new string('-', initString.Length); context.Logger.LogInformation("Initializing SharpHound at {time} on {date}", currentTime.ToShortTimeString(), currentTime.ToShortDateString()); // Check to make sure both LDAP options are set if either is set if (options.Password != null && options.Username == null || options.Username != null && options.Password == null) { context.Logger.LogTrace("You must specify both LdapUsername and LdapPassword if using these options!"); context.Flags.IsFaulted = true; return(context); } //Check some loop options if (!context.Flags.Loop) { return(context); } //If loop is set, ensure we actually set options properly if (context.LoopDuration == TimeSpan.Zero) { context.Logger.LogTrace("Loop specified without a duration. Defaulting to 2 hours!"); context.LoopDuration = TimeSpan.FromHours(2); } if (context.LoopInterval == TimeSpan.Zero) { context.LoopInterval = TimeSpan.FromSeconds(30); } if (!context.Flags.NoOutput) { var filename = context.ResolveFileName(Path.GetRandomFileName(), "", false); try { using (File.Create(filename)) { } File.Delete(filename); } catch (Exception e) { context.Logger.LogCritical("unable to write to target directory"); context.Flags.IsFaulted = true; } } context.Logger.LogTrace("Exiting initialize link"); return(context); }
public static async Task Main(string[] args) { var logger = new BasicLogger((int)LogLevel.Information); logger.LogInformation("This version of SharpHound is compatible with the 4.2 Release of BloodHound"); try { var parser = new Parser(with => { with.CaseInsensitiveEnumValues = true; with.CaseSensitive = false; with.HelpWriter = Console.Error; }); var options = parser.ParseArguments <Options>(args); await options.WithParsedAsync(async options => { if (!options.ResolveCollectionMethods(logger, out var resolved, out var dconly)) { return; } logger = new BasicLogger(options.Verbosity); var flags = new Flags { Loop = options.Loop, DumpComputerStatus = options.TrackComputerCalls, NoRegistryLoggedOn = options.SkipRegistryLoggedOn, ExcludeDomainControllers = options.ExcludeDCs, SkipPortScan = options.SkipPortCheck, SkipPasswordAgeCheck = options.SkipPasswordCheck, DisableKerberosSigning = options.DisableSigning, SecureLDAP = options.SecureLDAP, InvalidateCache = options.RebuildCache, NoZip = options.NoZip, NoOutput = false, Stealth = options.Stealth, RandomizeFilenames = options.RandomFileNames, MemCache = options.MemCache, CollectAllProperties = options.CollectAllProperties, DCOnly = dconly, PrettyPrint = options.PrettyPrint, SearchForest = options.SearchForest }; var ldapOptions = new LDAPConfig { Port = options.LDAPPort, DisableSigning = options.DisableSigning, SSL = options.SecureLDAP, AuthType = AuthType.Negotiate, DisableCertVerification = options.DisableCertVerification }; if (options.DomainController != null) { ldapOptions.Server = options.DomainController; } if (options.LDAPUsername != null) { if (options.LDAPPassword == null) { logger.LogError("You must specify LDAPPassword if using the LDAPUsername options"); return; } ldapOptions.Username = options.LDAPUsername; ldapOptions.Password = options.LDAPPassword; } IContext context = new BaseContext(logger, ldapOptions, flags) { DomainName = options.Domain, CacheFileName = options.CacheName, ZipFilename = options.ZipFilename, SearchBase = options.DistinguishedName, StatusInterval = options.StatusInterval, RealDNSName = options.RealDNSName, ComputerFile = options.ComputerFile, OutputPrefix = options.OutputPrefix, OutputDirectory = options.OutputDirectory, Jitter = options.Jitter, Throttle = options.Throttle, LdapFilter = options.LdapFilter, PortScanTimeout = options.PortCheckTimeout, ResolvedCollectionMethods = resolved, Threads = options.Threads, LoopDuration = options.LoopDuration, LoopInterval = options.LoopInterval, ZipPassword = options.ZipPassword, IsFaulted = false }; var cancellationTokenSource = new CancellationTokenSource(); context.CancellationTokenSource = cancellationTokenSource; // Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs eventArgs) // { // eventArgs.Cancel = true; // cancellationTokenSource.Cancel(); // }; // Create new chain links Links <IContext> links = new SharpLinks(); // Run our chain context = links.Initialize(context, ldapOptions); if (context.Flags.IsFaulted) { return; } context = links.TestConnection(context); if (context.Flags.IsFaulted) { return; } context = links.SetSessionUserName(options.OverrideUserName, context); context = links.InitCommonLib(context); context = links.GetDomainsForEnumeration(context); if (context.Flags.IsFaulted) { return; } context = links.StartBaseCollectionTask(context); context = await links.AwaitBaseRunCompletion(context); context = links.StartLoopTimer(context); context = links.StartLoop(context); context = await links.AwaitLoopCompletion(context); context = links.SaveCacheFile(context); links.Finish(context); }); } catch (Exception ex) { logger.LogError($"Error running SharpHound: {ex.Message}\n{ex.StackTrace}"); } }