def _auth_user(self, user_name, password, domain, server): # TODO: implement caching? # TODO: is this pre-test efficient, or should we simply try LogonUser()? # (Could this trigger account locking?) if not self._is_user(user_name, domain, server): return False htoken = None try: htoken = win32security.LogonUser( user_name, domain, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT, ) if not htoken: _logger.warning( "LogonUser('{}', '{}', '***') failed.".format(user_name, domain) ) return False except win32security.error as err: _logger.warning( "LogonUser('{}', '{}', '***') failed: {}".format(user_name, domain, err) ) return False finally: if htoken: htoken.Close() _logger.debug("User '{}' logged on.".format(user_name)) return True
def _VerifyWindowsAuth(self, username, password, domain): """Use Win32 APIs to authenticate. This uses Win32's LogonUser() which has special privilege requirements on some versions of Windows. Review: http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx Short version: WindowsXP doesn't require anything extra. Args: username: string username password: string password domain: string domain Returns: True if authenticated, False if authentication failed for bad auth Raises: common.AuthenticationError if other errors occur """ try: token = win32security.LogonUser( username, domain, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) return bool(token) except win32security.error, e: if e.args[0] == WINDOWS_LOGIN_ERROR_CODE: # login failure return False else: raise common.AuthenticationError(str(e))
def impersonate_user(self, username, password): """Impersonate the security context of another user.""" handler = win32security.LogonUser( username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(handler) handler.Close()
def CreateProcess(*args): startupinfo = args[-1] # If we are passed a LoginSTARTUPINFO, that means we need to use # CreateProcessAsUser instead of the CreateProcess in subprocess if isinstance(startupinfo, LoginSTARTUPINFO): # Gets the actual win32 STARTUPINFO object from LoginSTARTUPINFO win32startupinfo = startupinfo.win32startupinfo mkprocargs = args[:-1] + (win32startupinfo, ) login, domain, password = startupinfo.credentials # Get a user handle from the credentials userhandle = win32security.LogonUser( login, domain, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) try: # Return the pipes from CreateProcessAsUser return win32process.CreateProcessAsUser(userhandle, *mkprocargs) finally: # Close the userhandle before throwing whatever error arises userhandle.Close() return win32process.CreateProcess(*args)
def authenticate(self, handler, data): """Authenticate with Windows, and return the username if login is successful. Return None otherwise. """ domain = '.' if self.domain_to_add_to_username: if not '@' in data['username']: data['username'] += "@" + self.domain_to_add_to_username username = data['username'] if '@' in username: username, domain = username.split('@') try: token = win32security.LogonUser( username, domain, data['password'], win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) except win32security.error: # Invalid User return None # Incorrect Password if not token: return None return { 'name': data['username'], 'domain': domain, 'auth_state': { # Detach so the underlying winhandle stays alive 'auth_token': token.Detach(), }, }
def remote_authenticate(self, username, password, domain=None): if sys.platform == 'win32': import win32security, win32con, ntsecuritycon try: handle = win32security.LogonUser( username, domain, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) self.mLogger.info("Windows login succeeded.") # Get the PySID object for user's logon ID. tic = win32security.GetTokenInformation( handle, ntsecuritycon.TokenGroups) user_sid = None for sid, flags in tic: if flags & win32con.SE_GROUP_LOGON_ID: user_sid = sid break if user_sid is None: raise Exception('Failed to determine logon ID') return self.prepareAvatar( avatar.WindowsAvatar(handle, user_sid, username, domain)) except Exception, ex: self.mLogger.error("Windows login failed:") traceback.print_exc() return failure.Failure(error.UnauthorizedLogin(str(ex)))
def open(self): self.handle = win32security.LogonUser( self.user, self.domain, self.password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(self.handle) self.on = True
def test_Token_unimpersonate(): hToken = win32security.LogonUser("alice", "", "Passw0rd", win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(_tokens.Token(hToken).pyobject()) assert _tokens.token().Owner.pyobject() == alice win32security.RevertToSelf() assert _tokens.token().Owner.pyobject() == me
def impersonate(self): if self.as_user != '@': cred = self.cred_manager.get_cred(self.as_user) self.handle = winsec.LogonUser(cred.username, cred.domain, cred.password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) winsec.ImpersonateLoggedOnUser(self.handle)
def find_userName(self, password): for user in self.users: try: token = win32security.LogonUser(user['name'], self.domain, password , self.logontype, self.provider) return user['name'] except: pass return False
def impersonate_user(self, username, password): """impersonate user when operating file system """ handler = win32security.LogonUser( username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(handler) handler.Close()
def _authUser(self, username, password, domain, server): if not self._isUser(username, domain, server): return False try: htoken = win32security.LogonUser(username, domain, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) except win32security.error, err: #print err return False
def impersonate_user(self, username, password): if (username == "anonymous") and self.has_user('anonymous'): username = self.anon_user password = self.anon_pwd handler = win32security.LogonUser(username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(handler) handler.Close()
def install_client(self): logon = win32security.LogonUser( self.user.name, None, self.user.infos["password"], win32security.LOGON32_LOGON_INTERACTIVE, win32security.LOGON32_PROVIDER_DEFAULT) data = {} data["UserName"] = self.user.name hkey = win32profile.LoadUserProfile(logon, data) self.windowsProfileDir = win32profile.GetUserProfileDirectory(logon) self.windowsProgramsDir = shell.SHGetFolderPath( 0, shellcon.CSIDL_PROGRAMS, logon, 0) Logger.debug("startmenu: %s" % (self.windowsProgramsDir)) # remove default startmenu if os.path.exists(self.windowsProgramsDir): Platform.System.DeleteDirectory(self.windowsProgramsDir) os.makedirs(self.windowsProgramsDir) self.windowsDesktopDir = shell.SHGetFolderPath( 0, shellcon.CSIDL_DESKTOPDIRECTORY, logon, 0) self.appDataDir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, logon, 0) self.localAppDataDir = shell.SHGetFolderPath( 0, shellcon.CSIDL_LOCAL_APPDATA, logon, 0) Logger.debug("localAppdata: '%s'" % (self.localAppDataDir)) Logger.debug("appdata: '%s'" % (self.appDataDir)) win32profile.UnloadUserProfile(logon, hkey) win32api.CloseHandle(logon) self.set_user_profile_directories(self.windowsProfileDir, self.appDataDir) self.init_user_session_dir( os.path.join(self.appDataDir, "ulteo", "ovd")) if self.profile is not None and self.profile.hasProfile(): if not self.profile.mount(): return False self.profile.copySessionStart() if self.profile is not None and self.profile.mountPoint is not None: d = os.path.join(self.profile.mountPoint, self.profile.DesktopDir) self.cleanupShortcut(d) self.install_desktop_shortcuts() self.overwriteDefaultRegistry(self.windowsProfileDir) if self.profile is not None and self.profile.hasProfile(): self.profile.umount() self.succefully_initialized = True return True
def try_authorize(self, username, password): """Returns true is a user is authorised via PAM. @rtype: boolean """ try: htoken = win32security.LogonUser( username, "", password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) except win32security.error, err: return (False, None)
def logonUser(self): try: self.handel = win32security.LogonUser( self.username, self.domain, self.password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) win32security.ImpersonateLoggedOnUser(self.handel) return True except Exception as error: ExceptionManager.WriteException( str(error), "logonUser", exceptionFileName) return False
def windows_login(username, password, domain): """ Returns the authentication token of windows user :return: PyHandle token for using with other authenticated access """ token = win32security.LogonUser(username, domain, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) return token
def authorize(self, channel, userName, passWord): self.AdjustPrivilege(ntsecuritycon.SE_CHANGE_NOTIFY_NAME) self.AdjustPrivilege(ntsecuritycon.SE_ASSIGNPRIMARYTOKEN_NAME) self.AdjustPrivilege(ntsecuritycon.SE_TCB_NAME) try: logonHandle = win32security.LogonUser( userName, None, passWord, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) except pywintypes.error, ErrorMsg: return 0, ErrorMsg[2], None
def logonUser(loginString): """ Login as specified user and return handle. loginString: 'Domain\nUser\nPassword'; for local login use . or empty string as domain e.g. '.\nadministrator\nsecret_password' """ domain, user, passwd = loginString.split('\n') return win32security.LogonUser(user, domain, passwd, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT)
def autentica_usuario_no_ad(self, userName, senha, dominio): try: token = win32security.LogonUser(userName, dominio, senha, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) authenticacao = bool(token) return authenticacao except: FrmLogin() return False
def validate_authentication(self, username, password): if username == "anonymous": return self.anonymous_user is not None try: win32security.LogonUser(username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) except pywintypes.error: return False else: return True
def validate_authentication(self, username, password, handler): if username == "anonymous": if self.anonymous_user is None: raise AuthenticationFailed(self.msg_anon_not_allowed) return try: win32security.LogonUser(username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) except pywintypes.error: raise AuthenticationFailed(self.msg_wrong_password)
def test_Token_impersonate(): alice, system, type = win32security.LookupAccountName(None, "alice") hToken = win32security.LogonUser("alice", "", "Passw0rd", win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) token = _tokens.Token(hToken) try: token.impersonate() assert token.Owner.pyobject() == alice finally: win32security.RevertToSelf()
def win32check(user, pw): try: token = win32security.LogonUser( user, "ezesoft", pw, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) authenticated = bool(token) print("authenticated %r"% (authenticated)) return authenticated except: return False
def validate_authentication(self, username, password): if (username == "anonymous") and self.has_user('anonymous'): username = self.anon_user password = self.anon_pwd try: win32security.LogonUser(username, None, password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT) return True except pywintypes.error: return False
def __enter__(self) -> None: try: self.handle = win32security.LogonUser( self.username, self.domain, self.password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT, ) win32security.ImpersonateLoggedOnUser(self.handle) except pywintypes.error as exc: raise OSError(exc)
def authenticate(username: str, password: str, domain: str = '.', logon_type=win32con.LOGON32_LOGON_BATCH, logon_provider=win32con.LOGON32_PROVIDER_DEFAULT, **kwargs) -> bool: try: win32security.LogonUser(username, domain, password, logon_type, logon_provider) return True except pywintypes.error: return False
def test_Token_unimpersonate(self): hToken = win32security.LogonUser( "alice", "", "Passw0rd", win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT ) me = _tokens.token().Owner.pyobject() win32security.ImpersonateLoggedOnUser(_tokens.Token(hToken).pyobject()) self.assertEquals(_tokens.token().Owner.pyobject(), self.alice) win32security.RevertToSelf() self.assertEquals(_tokens.token().Owner.pyobject(), me)
def checkCredentials(user, passw): domain, username = win32api.GetUserNameEx( win32api.NameSamCompatible).split('\\') if user != username: return 'Wrong credentials. Please try again.' try: lg = win32security.LogonUser(user, domain, passw, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) except: return 'Wrong credentials. Please try again.' else: return 'Success'
def is_user_valid ( username, password, domain='GIG'): try: hUser = win32security.LogonUser ( username, domain, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT ) except win32security.error: return False else: return True