示例#1
0
        public string[] GetLDAPUserInformationByCommonName(string commonName)
        {
            Ldap ldap = Ldap.Instance;

            PrincipalContext ctx = ldap.GetPrincipalContext;

            userPrincipal = new UserPrincipal(ctx);
            searchUser    = new PrincipalSearcher();

            try
            {
                if (commonName != "" && commonName.Length != 0)
                {
                    userPrincipal.EmailAddress = $"{commonName}@zbc.dk";

                    searchUser.QueryFilter = userPrincipal;
                    userPrincipal          = (UserPrincipal)searchUser.FindOne();

                    userInfo[0] = userPrincipal.GivenName;
                    userInfo[1] = userPrincipal.Surname;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Exception: {ex.Message}");
                userInfo[0] = "User not found.";
                return(userInfo);
            }
            finally
            {
                ctx.Dispose();
            }
            return(userInfo);
        }
示例#2
0
        public static void Kerberoasting(string log, int sleep)
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;

            Lib.Logger logger = new Lib.Logger(currentPath + log);
            logger.SimulationHeader("T1558.003");


            if (sleep > 0)
            {
                logger.TimestampInfo(String.Format("Sleeping {0} seconds between each service ticket request", sleep));
            }

            try
            {
                //NetworkCredential cred = null;
                List <String> spns;
                spns = Ldap.GetSPNs();

                foreach (String spn in spns)
                {
                    Lib.SharpRoast.GetDomainSPNTicket(spn.Split('#')[0], spn.Split('#')[1], "", "", logger);
                    if (sleep > 0)
                    {
                        Thread.Sleep(sleep * 1000);
                    }
                }
                logger.SimulationFinished();
            }
            catch (Exception ex)
            {
                logger.SimulationFailed(ex);
            }
        }
示例#3
0
        private Ldap CreateLdap()
        {
            Ldap ldap = new Ldap(settings.Options.LdapHost, settings.Options.LdapPort);

            ldap.Bind(settings.Options.LdapManagerDN, settings.Options.LdapManagerPwd);
            return(ldap);
        }
示例#4
0
        public ActionResult Index()
        {
            ViewBag.MachineName        = Server.MachineName;
            ViewBag.AuthenticationType = Request?.LogonUserIdentity.AuthenticationType;
            ViewBag.ImpersonationLevel = Request?.LogonUserIdentity.ImpersonationLevel;
            ViewBag.Claims             = Request?.LogonUserIdentity.Claims;

            ViewBag.Groups = Request?.LogonUserIdentity.Groups.Select(x => new AdGroup()
            {
                Name  = AdGroup.ToName(x),
                Value = x.Value
            });


            Ldap ldapInfo = new Ldap();

            try
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                ldapInfo.ConnectedServer = ctx.ConnectedServer;
                ldapInfo.Container       = ctx.Container;

                var identity = UserPrincipal.FindByIdentity(ctx, Request.LogonUserIdentity.Name);
                ldapInfo.UserPrincipalName = identity.UserPrincipalName;
            }
            catch (Exception ex)
            {
                ldapInfo.ErrorMessage = ex.ToString();
            }

            ViewBag.LdapInfo = ldapInfo;

            return(View());
        }
示例#5
0
        public ActionResult Save(Ldap model)
        {
            DBEntities e = COREobject.i.Context;

            if (ModelState.IsValid)
            {
                // Záznam již existuje - pouze upravujeme
                if (!model.Id.Equals(null))
                {
                    Ldap row = e.Ldaps.Single(m => m.Id == model.Id);
                    row.Domain_Ntlm     = model.Domain_Ntlm;
                    row.Domain_Kerberos = model.Domain_Kerberos;
                    row.Domain_Server   = model.Domain_Server;
                    row.Bind_User       = model.Bind_User;
                    row.Bind_Password   = model.Bind_Password.Length > 0 ? model.Bind_Password : row.Bind_Password;
                    row.Use_SSL         = model.Use_SSL;
                    row.Active          = model.Active;

                    e.SaveChanges();
                }
                else
                {
                    e.Ldaps.Add(model);
                    e.SaveChanges();
                }
                return(RedirectToRoute("Nexus", new { @action = "Index" }));
            }
            else
            {
                return(View("~/Views/Nexus/LDAP/Form.cshtml", model));
            }
        }
 public CuponeraService(ICuponeraRepository cuponeraRepository, ILoggerManager logger, IMapper mapper, IOptions <Ldap> ldapSettings)
 {
     this._cuponeraRepository = cuponeraRepository;
     _logger       = logger;
     _mapper       = new MapperConfiguration(Config => { Config.CreateMissingTypeMaps = true; }).CreateMapper();
     _ldapSettings = ldapSettings.Value;
 }
        /// <summary>
        /// Authenticates the A duser.
        /// </summary>
        /// <remarks>
        /// Sequence Diagram:<br/>
        ///     <img src="SequenceDiagrams/SD_PrintReleaseDevice.Browser.SelfRegistration.AuthenticateADuser.jpg"/>
        /// </remarks>
        private void AuthenticateADuser()
        {
            string username     = TextBoxUserName.Text.Trim();
            string userPassword = TextBoxPassword.Text.Trim();
            string userDomain   = TextBoxDomain.Text;

            string domainName     = string.Empty;
            string domainUserName = string.Empty;
            string domainPassword = string.Empty;

            string ActiveDirectorySettings = ApplicationSettings.ProvideActiveDirectorySettings(userDomain, ref domainName, ref domainUserName, ref domainPassword);

            if (Ldap.UserExists(username, userDomain, domainUserName, domainPassword))
            {
                if (AppAuthentication.isValidUser(username, userPassword, userDomain, userSource))
                {
                    BuildFutureLoginForm();
                }
                else
                {
                    TableCommunicator.Visible             = true;
                    TableSelfRegistrationControls.Visible = false;
                    LabelCommunicatorNote.Text            = Localization.GetServerMessage(Constants.APPLICATION_TYPE_OSA_CLASSIC, deviceCulture, "INVALID_PASSWORD");
                    return;
                }
            }
            else
            {
                isClearAllFields                      = true;
                TableCommunicator.Visible             = true;
                TableSelfRegistrationControls.Visible = false;
                LabelCommunicatorNote.Text            = Localization.GetServerMessage(Constants.APPLICATION_TYPE_OSA_CLASSIC, deviceCulture, "INVALID_USER_TRY_AGAIN");
                return;
            }
        }
示例#8
0
        private static IEnumerable <LdapResult> Sync(Ldap ldap, string pattern)
        {
            logger.Info(nameof(LdapSyncTester), $"processing... sync pattern ={pattern}");
            var directorySearcher = DirectorySearcher(
                ldap.LdapSyncUser,
                ldap.LdapSyncPassword,
                ldap);

            directorySearcher.Filter   = pattern;
            directorySearcher.PageSize = 1000;
            var results = directorySearcher.FindAll();

            foreach (SearchResult result in results)
            {
                DirectoryEntry entry = result.Entry(
                    ldap.LdapSyncUser,
                    ldap.LdapSyncPassword);

                string loginId = entry.Property(ldap.LdapSearchProperty);
                logger.Info(nameof(LdapSyncTester), $"processing...({loginId})");

                var ldapResult = new LdapResult()
                {
                    LoginId            = entry.Property(ldap.LdapSearchProperty),
                    Name               = Name(loginId, entry, ldap: ldap),
                    Enabled            = Enabled(entry, ldap)?"True":"False",
                    MailAddress        = entry.Property(ldap.LdapMailAddress, ldap.LdapMailAddressPattern),
                    UserCode           = entry.Property(ldap.LdapUserCode, ldap.LdapUserCodePattern),
                    DeptCode           = entry.Property(ldap.LdapDeptCode, ldap.LdapDeptCodePattern),
                    DeptName           = entry.Property(ldap.LdapDeptName, ldap.LdapDeptNamePattern),
                    ExtendedAttributes = string.Join(", ", ldap.LdapExtendedAttributes?.Select(attr => entry.Property(attr.Name, attr.Pattern)) ?? new string[0]),
                };
                yield return(ldapResult);
            }
        }
示例#9
0
        public async Task Invoke(HttpContext httpContext)
        {
            const string enabled = "Enabled";

            if (!httpContext.Session.Keys.Any(key => key == enabled))
            {
                AspNetCoreCurrentRequestContext.AspNetCoreHttpContext.Current.Session.Set("SessionGuid", System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(Strings.NewGuid())));
                httpContext.Session.Set(enabled, new byte[] { 1 });
                var context = SessionStartContext();
                SessionUtilities.SetStartTime(context: context);
                if (WindowsAuthenticated(context))
                {
                    Ldap.UpdateOrInsert(
                        context: context,
                        loginId: context.LoginId);
                    context.Set();
                }
                if (context.Authenticated)
                {
                    StatusesInitializer.Initialize(context: context);
                }
                switch (httpContext.Request.Path.Value.ToLower())
                {
                case "~/backgroundtasks/do":
                case "~/reminderschedules/remind":
                    break;

                default:
                    break;
                }
            }
            await _next.Invoke(httpContext);
        }
示例#10
0
 private static DirectorySearcher DirectorySearcher(
     string loginId, string password, Ldap ldap)
 {
     return(new DirectorySearcher(loginId != null && password != null
         ? new DirectoryEntry(ldap.LdapSearchRoot, loginId, password)
         : new DirectoryEntry(ldap.LdapSearchRoot)));
 }
示例#11
0
        public static void Kerberoasting(string log, int sleep = 0)
        {
            string currentPath = AppDomain.CurrentDomain.BaseDirectory;

            Lib.Logger logger = new Lib.Logger(currentPath + log);
            logger.SimulationHeader("T1208");
            //logger.TimestampInfo(String.Format("Starting T1208 Simulation on {0}", Environment.MachineName));
            //logger.TimestampInfo(String.Format("Simulation agent running as {0} with PID:{1}", System.Reflection.Assembly.GetEntryAssembly().Location, Process.GetCurrentProcess().Id));
            if (sleep > 0)
            {
                Console.WriteLine("[*] Sleeping {0} seconds between attempt", sleep);
            }

            try
            {
                //NetworkCredential cred = null;
                List <String> spns;
                spns = Ldap.GetSPNs();

                foreach (String spn in spns)
                {
                    Lib.SharpRoast.GetDomainSPNTicket(spn.Split('#')[0], spn.Split('#')[1], "", "", logger);
                    if (sleep > 0)
                    {
                        Thread.Sleep(sleep * 1000);
                    }
                }
                logger.SimulationFinished();
            }
            catch (Exception ex)
            {
                logger.SimulationFailed(ex);
            }
        }
示例#12
0
        private void dg_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            int sid = int.Parse(e.Item.Cells[0].Text);

            Ldap.SyncLogDelete(sid);
            Response.Redirect("~/Admin/LdapLogs.aspx");
        }
示例#13
0
        protected void Session_Start()
        {
            Session["Enabled"] = true;
            var context = SessionStartContext();

            SessionUtilities.SetStartTime(context: context);
            if (WindowsAuthenticated(context))
            {
                Ldap.UpdateOrInsert(
                    context: context,
                    loginId: context.LoginId);
                context.Set();
            }
            if (context.Authenticated)
            {
                StatusesInitializer.Initialize(context: context);
            }
            switch (Request.AppRelativeCurrentExecutionFilePath.ToLower())
            {
            case "~/backgroundtasks/do":
            case "~/reminderschedules/remind":
                break;

            default:
                new SysLogModel(context: context).Finish(context: context);
                break;
            }
        }
        /// <summary>
        /// Fixed:
        /// </summary>
        public bool Authenticate()
        {
            var ret = false;

            switch (Parameters.Authentication.Provider)
            {
            case "LDAP":
                ret = Ldap.Authenticate(LoginId, Forms.Data("Users_Password"));
                if (ret)
                {
                    Get(SiteSettingsUtilities.UsersSiteSettings(),
                        where : Rds.UsersWhere().LoginId(LoginId));
                }
                break;

            case "Extension":
                var user = Extension.Authenticate(LoginId, Password);
                ret = user != null;
                if (ret)
                {
                    Get(SiteSettingsUtilities.UsersSiteSettings(),
                        where : Rds.UsersWhere()
                        .TenantId(user.TenantId)
                        .UserId(user.Id));
                }
                break;

            default:
                ret = GetByCredentials(LoginId, Password, Forms.Int("SelectedTenantId"));
                break;
            }
            return(ret);
        }
示例#15
0
        public static List <Claim> ValidaAcesso(Ldap ldap, LoginData loginData, List <PermissionGroup> grupos)
        {
            List <Claim> claims = new List <Claim>();

            LdapConnection ldapConnection = ldapConnection = new LdapConnection();

            ldapConnection.Connect(ldap.host, ldap.port);
            ldapConnection.Bind(ldap.ldapVersion, ldap.bindLogin, ldap.bindPassword);

            String usuarioDN = GetDNUsuario(ldapConnection, ldap, loginData);

            if (usuarioDN == null)
            {
                return(null);
            }

            Boolean validaUsuarioSenha = ValidaUsuarioSenha(ldap, loginData, usuarioDN);

            if (validaUsuarioSenha)
            {
                ldapConnection.Disconnect();
                return(ValidaPermissaoGrupo(ldap, loginData, usuarioDN, grupos));
            }

            ldapConnection.Disconnect();
            return(null);
        }
示例#16
0
 private SignInResult SignIn(string uid, string password)
 {
     using (Ldap ldap = new Ldap(settings.Options.LdapHost, settings.Options.LdapPort))
     {
         ldap.Bind(settings.Options.LdapManagerDN, settings.Options.LdapManagerPwd);
         var entry = ldap.SearchOne(settings.Options.LdapPeopleOU, LdapScope.ONE, string.Format("uid={0}", uid));
         if (entry == null)
         {
             ModelState.AddModelError(string.Empty, "工号不存在");
             return(SignInResult.Failed);
         }
         try
         {
             ldap.Bind(entry.DN, password);
         }
         catch
         {
             ModelState.AddModelError(string.Empty, "密码不正确");
             return(SignInResult.Failed);
         }
         var name     = entry.getAttribute("cn") == null ? string.Empty : entry.getAttribute("cn").StringValue;
         var mail     = entry.getAttribute("mail") == null ? string.Empty : entry.getAttribute("cn").StringValue;
         var identity = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationType);
         identity.AddClaim(new Claim(ClaimTypes.Name, name));
         identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, uid));
         identity.AddClaim(new Claim(ClaimTypes.Email, mail));
         Context.Authentication.SignIn(string.Empty, new ClaimsPrincipal(identity));
         return(SignInResult.Success);
     }
 }
示例#17
0
        private void AuthenticateADuser(string userName, string password, string selectedDomain)
        {
            string username     = userName;
            string userPassword = password;
            string userDomain   = selectedDomain;

            string domainName     = string.Empty;
            string domainUserName = string.Empty;
            string domainPassword = string.Empty;

            string ActiveDirectorySettings = ApplicationSettings.ProvideActiveDirectorySettings(userDomain, ref domainName, ref domainUserName, ref domainPassword);

            if (Ldap.UserExists(username, userDomain, domainUserName, domainPassword))
            {
                if (AppAuthentication.isValidUser(username, userPassword, userDomain, userSource))
                {
                    AddUserDetails(userName, userPassword, userDomain);
                }
                else
                {
                    Response.Redirect("MessageForm.aspx?FROM=SelfRegistration.aspx&MESS=InvalidPassword");
                    // LabelCommunicatorNote.Text = Localization.GetServerMessage(Constants.APPLICATION_TYPE_OSA_CLASSIC, deviceCulture, "INVALID_PASSWORD");
                }
            }
            else
            {
                Response.Redirect("MessageForm.aspx?FROM=SelfRegistration.aspx&MESS=invalidUserTryAgain");
                //LabelCommunicatorNote.Text = Localization.GetServerMessage(Constants.APPLICATION_TYPE_OSA_CLASSIC, deviceCulture, "INVALID_USER_TRY_AGAIN");
            }
        }
示例#18
0
        private static bool Enabled(DirectoryEntry entry, Ldap ldap)
        {
            var accountDisabled = 2;

            return
                (!ldap.LdapExcludeAccountDisabled ||
                 (entry.Properties["UserAccountControl"].Value.ToLong() & accountDisabled) == 0);
        }
        private static bool Enabled(SearchResult result, Ldap ldap)
        {
            var accountDisabled = 2;

            return
                (!ldap.LdapExcludeAccountDisabled || !result.Properties.Contains("UserAccountControl") ||
                 (result.Properties["UserAccountControl"].ToLong() & accountDisabled) == 0);
        }
示例#20
0
        public static List <User> GetUserTargets(PlaybookTask playbook_task, Logger logger)
        {
            PrincipalContext context;
            string           dc;
            List <User>      targetusers = new List <User>();


            switch (playbook_task.user_target_type)
            {
            case 1:
                logger.TimestampInfo("Targeting playbook defined users");
                foreach (string user in playbook_task.user_targets)
                {
                    User nuser = new User(user);
                    targetusers.Add(nuser);
                }
                break;

            case 2:
                context = new PrincipalContext(ContextType.Domain);
                dc      = context.ConnectedServer;
                logger.TimestampInfo("Targeting random domain users");
                targetusers = Ldap.GetADUsers(playbook_task.user_target_total, logger, dc, true);
                logger.TimestampInfo(String.Format("Obtained {0} user records", targetusers.Count));

                break;

            case 3:
                logger.TimestampInfo("Targeting randomly generated users");
                targetusers = Targets.GetRandomUsernames(playbook_task.user_target_total, new Random());
                break;

            case 4:
                logger.TimestampInfo("Targeting administrative accounts (adminCount=1) ");
                targetusers = Ldap.GetADAdmins(playbook_task.user_target_total, logger);
                logger.TimestampInfo(String.Format("Obtained {0} user records", targetusers.Count));
                break;

            case 5:
                logger.TimestampInfo("Targeting domain admins");
                targetusers = Ldap.GetDomainAdmins(logger);
                logger.TimestampInfo(String.Format("Obtained {0} user records", targetusers.Count));
                break;

            case 6:
                context = new PrincipalContext(ContextType.Domain);
                dc      = context.ConnectedServer;
                logger.TimestampInfo("Targeting disabled users");
                targetusers = Ldap.GetADUsers(playbook_task.user_target_total, logger, dc, false);
                logger.TimestampInfo(String.Format("Obtained {0} user records", targetusers.Count));
                break;

            default:
                return(targetusers);
            }

            return(targetusers);
        }
示例#21
0
 public SessionController(IOptions <ApplicationOptions> options,
                          IEmployeeRepository employeeRepository,
                          IAdministratorRepository administratorRepository)
     : base(options)
 {
     _employeeRepo   = employeeRepository;
     _adminRepo      = administratorRepository;
     _authentication = new Ldap(Options, _adminRepo.Get());
 }
示例#22
0
        public static List <Computer> GetDomainRandomTargets(int count)
        {
            List <Computer> targets = new List <Computer>();

            Console.WriteLine("[*] Obtaining domain random targets ...");
            targets = Ldap.GetADComputers(count);

            return(targets);
        }
示例#23
0
        public static List <Computer> GetDomainRandomTargets(int count, Logger logger)
        {
            List <Computer> targets = new List <Computer>();

            logger.TimestampInfo("Obtaining domain random targets ...");
            targets = Ldap.GetADComputers(count, logger);

            return(targets);
        }
示例#24
0
        public ActionResult Delete(int id)
        {
            DBEntities e   = COREobject.i.Context;
            Ldap       row = e.Ldaps.Single(m => m.Id == id);

            e.Ldaps.Remove(row);
            e.SaveChanges();

            return(RedirectToRoute("Nexus", new { @action = "Index" }));
        }
示例#25
0
        public string LdapGetCommonName(string firstName, string lastName)
        {
            Ldap ldap = Ldap.Instance;

            PrincipalContext ctx = ldap.GetPrincipalContext;

            userPrincipal = new UserPrincipal(ctx);
            searchUser    = new PrincipalSearcher();

            try
            {
                if ((firstName != "" && firstName.Length != 0) && (lastName != "" && lastName.Length != 0))
                {
                    userPrincipal.GivenName = firstName;
                    userPrincipal.Surname   = lastName;

                    searchUser.QueryFilter = userPrincipal;
                    PrincipalSearchResult <Principal> results = searchUser.FindAll();

                    foreach (UserPrincipal name in results)
                    {
                        if (!name.Name.Contains("zbc"))
                        {
                            return(name.Name);
                        }
                    }
                    return($"No Account Found.");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Exception: {ex.Message}");
                userInfo = "User not found.";
                return(userInfo);
            }
            finally
            {
                if (ctx != null)
                {
                    ctx.Dispose();
                    Debug.WriteLine($"Disposed: Context");
                }
                if (userPrincipal != null)
                {
                    userPrincipal.Dispose();
                    Debug.WriteLine($"Disposed: User Principal.");
                }
                if (searchUser != null)
                {
                    searchUser.Dispose();
                    Debug.WriteLine($"Disposed: Search User.");
                }
            }
            return(userInfo);
        }
示例#26
0
        public static List <Computer> GetDomainNeighborTargets(int count, Lib.Logger logger)
        {
            List <Computer>  targets = new List <Computer>();
            PrincipalContext context = new PrincipalContext(ContextType.Domain);
            string           dc      = context.ConnectedServer;

            logger.TimestampInfo("Obtaining domain neighbor targets ...");
            targets = Ldap.GetADComputers(count, logger, dc);
            //Console.WriteLine("[*] Finished");
            return(targets);
        }
示例#27
0
        private async Task CreateLdapConnection()
        {
            ldap = await ldapRepository.Get();

            String ldapUser     = Lib.Cipher.Decrypt(ldap.BindLogin, ldap.ChangeDate.ToString());
            String ldapPassword = Lib.Cipher.Decrypt(ldap.BindPassword, ldap.ChangeDate.ToString());

            ldapConnection = new LdapConnection();
            ldapConnection.Connect(ldap.Server, ldap.Port);
            ldapConnection.Bind(ldap.LdapVersion, ldapUser, ldapPassword);
        }
示例#28
0
        public LoginModule(PeopleContext people, Ldap ldap)
        {
            _people = people;
            _ldap   = ldap;

            Get["/login"] = parameters =>
            {
                // Called when the user visits the login page or is redirected here because
                // an attempt was made to access a restricted resource. It should return
                // the view that contains the login form
                return(View["login"]);
            };

            Get["/logoff"] = parameters =>
            {
                // Called when the user clicks the sign out button in the application. Should
                // perform one of the Logout actions (see below)
                return(this.LogoutAndRedirect("/"));
            };

            Post["/login"] = parameters =>
            {
                // Called when the user submits the contents of the login form. Should
                // validate the user based on the posted form data, and perform one of the
                // Login actions (see below)
                var username = (string)Request.Form.username;
                var password = (string)Request.Form.password;

                // Authenticate user against AD
                if (!_ldap.IsAuthenticated(ConfigurationManager.AppSettings.Get("ldap-domain"), username, password))
                {
                    return(View["login", "Unable to validate your account. Please contact the dev team at [email protected]"]);
                }

                var user = _people.People.FirstOrDefault(p => p.AdUser == username && !p.Hidden && !p.Retired);
                if (user == null)
                {
                    // User was not found in the database, register the ad user.
                    var newUser = ldap.GetUser(username);
                    user = new Person
                    {
                        Id      = Guid.NewGuid(),
                        AdUser  = username,
                        Created = DateTime.Now,
                        Email   = newUser.Properties["mail"][0].ToString(),
                        Name    = newUser.Properties["displayName"][0].ToString()
                    };
                    user = _people.People.Add(user);
                    _people.SaveChanges();
                }

                return(this.LoginAndRedirect(user.Id, null, "/profile"));
            };
        }
示例#29
0
        public LoginModule(PeopleContext people, Ldap ldap)
        {
            _people = people;
            _ldap = ldap;

            Get["/login"] = parameters =>
            {
                // Called when the user visits the login page or is redirected here because
                // an attempt was made to access a restricted resource. It should return
                // the view that contains the login form
                return View["login"];
            };

            Get["/logoff"] = parameters =>
            {
                // Called when the user clicks the sign out button in the application. Should
                // perform one of the Logout actions (see below)
                return this.LogoutAndRedirect("/");
            };

            Post["/login"] = parameters =>
            {
                // Called when the user submits the contents of the login form. Should
                // validate the user based on the posted form data, and perform one of the
                // Login actions (see below)
                var username = (string) Request.Form.username;
                var password = (string) Request.Form.password;

                // Authenticate user against AD
                if (!_ldap.IsAuthenticated(ConfigurationManager.AppSettings.Get("ldap-domain"), username, password))
                {
                    return View["login", "Unable to validate your account. Please contact the dev team at [email protected]"];
                }

                var user = _people.People.FirstOrDefault(p => p.AdUser == username && !p.Hidden && !p.Retired);
                if (user == null)
                {
                    // User was not found in the database, register the ad user.
                    var newUser = ldap.GetUser(username);
                    user = new Person
                    {
                        Id = Guid.NewGuid(),
                        AdUser = username,
                        Created = DateTime.Now,
                        Email = newUser.Properties["mail"][0].ToString(),
                        Name = newUser.Properties["displayName"][0].ToString()
                    };
                    user = _people.People.Add(user);
                    _people.SaveChanges();
                }

                return this.LoginAndRedirect(user.Id, null, "/profile");
            };
        }
示例#30
0
        public static List <User> GetUserTargets(int usertype, int nuser)
        {
            List <User> targetusers = new List <User>();

            /*
             * string logonserver, dnsdomain, dc;
             * logonserver = Environment.GetEnvironmentVariable("logonserver").Replace("\\", "");
             * dnsdomain = Environment.GetEnvironmentVariable("USERDNSDOMAIN");
             * dc = logonserver + "." + dnsdomain;
             */

            PrincipalContext context = new PrincipalContext(ContextType.Domain);
            string           dc      = context.ConnectedServer;


            switch (usertype)
            {
            case 1:

                Console.WriteLine("[*] Targeting domain neighbor users");
                targetusers = Ldap.GetADUsers(nuser, dc, true);
                break;

            case 2:
                Console.WriteLine("[*] Targeting domain foreign users");
                targetusers = Ldap.GetADUsers(nuser, "", true);
                break;

            case 3:
                Console.WriteLine("[*] Targeting disabled users");
                targetusers = Ldap.GetADUsers(nuser, dc, false);
                break;

            case 4:
                Console.WriteLine("[*] Targeting administrative accounts (adminCount=1) ");
                targetusers = Ldap.GetADAdmins(nuser);
                break;

            case 5:
                Console.WriteLine("[*] Targeting domain admins");
                targetusers = Ldap.GetDomainAdmins();
                break;

            case 6:
                targetusers = Targets.GetRandomUsernames(nuser);
                break;

            default:
                return(targetusers);
            }

            return(targetusers);
        }
示例#31
0
        public static List <Computer> GetDomainNeighborTargets(int count)
        {
            List <Computer> targets     = new List <Computer>();
            string          logonserver = Environment.GetEnvironmentVariable("logonserver").Replace("\\", "");
            string          dnsdomain   = Environment.GetEnvironmentVariable("USERDNSDOMAIN");
            string          dc          = logonserver + "." + dnsdomain;

            Console.WriteLine("[*] Obtaining domain neighbor targets ...");
            targets = Ldap.GetADComputers(count, dc);

            return(targets);
        }
示例#32
0
        public string GetEMailByLogin(string login)
        {
            Ldap ldap = new Ldap();

            return ldap.GetEmail(login);
        }