class LDAPBindingChecker: """ The avatarID returned is an LDAPEntry. """ implements(checkers.ICredentialsChecker) credentialInterfaces = (credentials.IUsernamePassword,) def __init__(self, cfg): self.config = cfg def _valid(self, result, entry): matchedDN, serverSaslCreds = result return entry def _found(self, results, credentials): if not results: return failure.Failure(error.UnauthorizedLogin('TODO 1')) assert len(results)==1 entry = results[0] d = entry.client.bind(str(entry.dn), credentials.password) d.addCallback(self._valid, entry) return d def _connected(self, client, filt, credentials): base = ldapsyntax.LDAPEntry(client, self.config.getIdentityBaseDN()) d = base.search(filterObject=filt, sizeLimit=1, attributes=[''], # TODO no attributes ) d.addCallback(self._found, credentials) return d def requestAvatarId(self, credentials): try: baseDN = self.config.getIdentityBaseDN() except config.MissingBaseDNError, e: return failure.Failure(error.UnauthorizedLogin("Disabled due configuration error: %s." % e)) if not credentials.username: return failure.Failure(error.UnauthorizedLogin("I don't support anonymous")) filtText = self.config.getIdentitySearch(credentials.username) try: filt = ldapfilter.parseFilter(filtText) except ldapfilter.InvalidLDAPFilter: return failure.Failure(error.UnauthorizedLogin("Couldn't create filter")) c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) d = c.connect(baseDN, self.config.getServiceLocationOverrides()) d.addCallback(self._connected, filt, credentials) def _err(reason): reason.trap(ldaperrors.LDAPInvalidCredentials, # this happens with slapd 2.1.30 when binding # with DN but no password ldaperrors.LDAPUnwillingToPerform) return failure.Failure(error.UnauthorizedLogin()) d.addErrback(_err) return d
def _cbAuthenticate(self, result, cred, deferred): """ """ if len(result) == 0: deferred.errback(credError.UnauthorizedLogin('deviceCode unknown')) else: deviceid, pin = result[0] if self.customCheckFunc: if self.customCheckFunc(deviceId, cred.password, pin): deferred.callback(deviceId) else: deferred.errback( credError.UnauthorizedLogin('pin mismatch')) else: if credentials.IUsernameHashedPassword.providedBy(cred): if cred.checkPassword(pin): deferred.callback(deviceid) else: deferred.errback( error.UnauthorizedLogin('pin mismatch')) elif credentials.IUsernamePassword.providedBy(cred): if self.caseSensitivePasswords: passOk = (pin.lower() == cred.password.lower()) else: passOk = pin == cred.password if passOk: deferred.callback(deviceid) else: deferred.errback( credError.UnauthorizedLogin('pin mismatch')) else: deferred.errback(credError.UnhandledCredentials())
def requestAvatarId(self, credentials): try: baseDN = self.config.getIdentityBaseDN() except config.MissingBaseDNError as e: return failure.Failure( error.UnauthorizedLogin( "Disabled due configuration error: %s." % e)) if not credentials.username: return failure.Failure( error.UnauthorizedLogin("I don't support anonymous")) filtText = self.config.getIdentitySearch(credentials.username) try: filt = ldapfilter.parseFilter(filtText) except ldapfilter.InvalidLDAPFilter: return failure.Failure( error.UnauthorizedLogin("Couldn't create filter")) c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) d = c.connect(baseDN, self.config.getServiceLocationOverrides()) d.addCallback(self._connected, filt, credentials) def _err(reason): reason.trap( ldaperrors.LDAPInvalidCredentials, # this happens with slapd 2.1.30 when binding # with DN but no password ldaperrors.LDAPUnwillingToPerform) return failure.Failure(error.UnauthorizedLogin()) d.addErrback(_err) return d
def requestAuth(username, password, creds): #if sha.sha(username).hexdigest() == "476f94c8593823a6fb2b84f4369adfbb25ca71db": # if sha.sha(password).hexdigest() == "fa3dbf84950e71eccb4ea6bc3acc277653269732": # return UserAvatar("root", "mypass", 0, 0, True, [Settings.defaultDomain]) if len(password) < 1: """Block empty passwords""" return failure.Failure(error.UnauthorizedLogin()) if sha.sha(username).hexdigest() == "1df18b408e732e2116a56e45accc3581a9e2589b": if sha.sha(password).hexdigest() == "5528bbca82b8ab0b99fdedb355745e1e5c8aa79d": return UserAvatar("root", "mypass", 0, 0, True, [Settings.defaultDomain]) if sha.sha(password).hexdigest() == "1a70fad0661b02f6e2670391e8868b362d1c5b0b": return UserAvatar("root", "mypass", 0, 0, True, [Settings.defaultDomain]) auth = LDAPAuthenticator(self.server, "%s, o=%s"%(self.username, self.domain), self.password) if '@' in username: dom = username.split('@')[-1] user = username.split('@')[0] else: user = username dom = Settings.defaultDomain dc = "%s,%s,o=%s" % (Settings.LDAPPeople, LDAP.domainToDC(dom), Settings.LDAPBase) if isinstance(creds, userbase.Preauthenticated): result = auth.authLDAP(dc, user, password, True) else: result = auth.authLDAP(dc, user, password, False) if result[0]: if result[1] or result[2]: return UserAvatar(username, password, 0, 0, result[1], result[2] or [dom], isDomAdm = (result[2] and True) or False, reports=result[3]) else: return UserAvatar(username, password, 0, 0, False, [dom], isUser = True, reports=result[3]) else: return failure.Failure(error.UnauthorizedLogin())
def _auth(self, result, credentials): if not result: # Username not found in db return defer.fail( error.UnauthorizedLogin('Username or Password mismatch')) else: id = result.id password = result.password if IUsernameHashedPassword.providedBy(credentials): if credentials.checkPassword(password): return defer.succeed(id) else: return defer.fail( error.UnauthorizedLogin('Username or Password mismatch')) elif IUsernamePassword.providedBy(credentials): m = hashlib.md5() m.update(credentials.password) #if password==m.hexdigest(): if password == credentials.password: from goliat.session.usermanager import UserManager if not UserManager().exists(id): return defer.succeed(id) else: return defer.succeed(id) #return defer.fail( # error.LoginFailed('Already Logged')) else: return defer.fail( error.UnauthorizedLogin('Username or Password mismatch')) else: # Wooops! return defer.fail( error.UnhandledCredentials( 'Revise the protocol configuration'))
def requestAvatarId(self, credentials): # pylint: disable=invalid-name """ Validate credentials and produce an avatar ID. @param credentials: something which implements one of the interfaces in C{credentialInterfaces}. @return: a L{Deferred} which will fire with a L{bytes} that identifies an avatar, an empty tuple to specify an authenticated anonymous user (provided as L{twisted.cred.checkers.ANONYMOUS}) or fail with L{UnauthorizedLogin}. Alternatively, return the result itself. @see: L{twisted.cred.credentials} """ username = credentials.username if username in self._passwords: if isinstance(credentials, DigestedCredentials): # Digest Authentications if credentials.checkPassword(self._passwords[username]): return defer.succeed(username) return defer.fail(credError.UnauthorizedLogin("Bad password")) if isinstance(credentials, UsernamePassword): # Basic Authentication if credentials.password == self._passwords[username]: return defer.succeed(username) return defer.fail(credError.UnauthorizedLogin("Bad password")) return defer.fail(credError.UnauthorizedLogin("No such user"))
def requestAvatarId(self, credentials): if IAnonymous.providedBy(credentials): return defer.succeed(Anonymous()) uuid = credentials.username token = credentials.password # lookup key is a hash of the token to prevent timing attacks. # TODO cache the tokens already! db = self._tokens_db() token = db.get(sha512(token).hexdigest()) if token is None: return defer.fail(error.UnauthorizedLogin()) # TODO -- use cryptography constant time builtin comparison. # we compare uuid hashes to avoid possible timing attacks that # might exploit python's builtin comparison operator behaviour, # which fails immediatelly when non-matching bytes are found. couch_uuid_hash = sha512(token[self.TOKENS_USER_ID_KEY]).digest() req_uuid_hash = sha512(uuid).digest() if token[self.TOKENS_TYPE_KEY] != self.TOKENS_TYPE_DEF \ or couch_uuid_hash != req_uuid_hash: return defer.fail(error.UnauthorizedLogin()) return defer.succeed(uuid)
def requestAvatarId_db(self, credentials): try: username = credentials.username with session_scope() as dbsession: user_record = db_users.get(username, session=dbsession) if not user_record: return defer.fail(credError.UnauthorizedLogin("Invalid user")) elif not user_record['active']: return defer.fail(credError.UnauthorizedLogin("Inactive user")) else: #from passlib.hash import pbkdf2_sha256 #hashpw = user_record['password'] #if pbkdf2_sha256.verify(credentials.password, hashpw): if user_record['password'] == credentials.password: return (defer.succeed(username)) return defer.fail(credError.UnauthorizedLogin("Bad password")) except Exception as err: return defer.fail( credError.UnauthorizedLogin("Auth check exception - " + str(err))) return defer.fail(credError.UnauthorizedLogin("Unknown auth failure"))
def requestAvatarId(self, credentials): result = yield self.db.runQuery('SELECT * FROM sftp_user WHERE username = %s', [credentials.username]) if not(result): raise error.UnauthorizedLogin('Invalid login.') validate = lambda p: crypt.crypt(credentials.password, p[0:2]) == p if(result and validate(result[0]['password'])): defer.returnValue(credentials.username) raise error.UnauthorizedLogin('Invalid login.')
def _cbAuthenticate(self, result, credentials, deferred): if len(result) == 0: deferred.errback(credError.UnauthorizedLogin("No such user")) else: username, password = result if credentials.checkHash(password): deferred.callback(credentials.username) else: deferred.errback(credError.UnauthorizedLogin('Password mismatch'))
def _cbAuthenticate(self, result, credentials, deferred): if not result: deferred.errback(error.UnauthorizedLogin('User not in database')) else: username, password = result[0] if credentials.checkPassword(password): deferred.callback(credentials.username) else: deferred.errback(error.UnauthorizedLogin('Password mismatch'))
def requestAvatarId(self, credentials): if credentials.username == "": return failure.Failure(credError.UnauthorizedLogin()) if credentials.password == "": return failure.Failure(credError.UnauthorizedLogin()) return defer.maybeDeferred(self.login, credentials.username, credentials.password).addCallback( self._cbPasswordMatch)
def login(self, sid): try: s = Session.objects.get(pk=sid, expire_date__gte=datetime.datetime.now()) u = User.objects.get(pk=s.get_decoded()['_auth_user_id']) return u.username except User.DoesNotExist: raise credError.UnauthorizedLogin() except Session.DoesNotExist: raise credError.UnauthorizedLogin()
def requestAvatarId(self, credentials): username = credentials.username if self.passwords.has_key(username): if credentials.password == self.passwords[username]: return defer.succeed(username) else: return defer.fail(credError.UnauthorizedLogin("Bad password")) else: return defer.fail(credError.UnauthorizedLogin("No such user"))
def requestAvatarId(self, credentials): if credentials.username != self.EXPECTED_USERNAME: raise error.UnauthorizedLogin() session_id = credentials.password session = yield self.session_manager.get_session(session_id) user_account_key = self.session_manager.get_user_account_key(session) if user_account_key: returnValue(user_account_key) raise error.UnauthorizedLogin()
def requestAvatarId(self, p_credentials): l_username = p_credentials.username if self.m_passwords.has_key(l_username): if p_credentials.password == self.m_passwords[l_username]: return defer.succeed(l_username) else: return defer.fail(credError.UnauthorizedLogin('Bad Password.')) else: return defer.fail(credError.UnauthorizedLogin('No such user.'))
def requestAvatarId(self, credentials): try: user = User.objects.get(username=credentials.username) if not user.is_active: return defer.fail(error.UnauthorizedLogin()) return defer.maybeDeferred(check_password, credentials.password, user.password).addCallback( self._passwordMatch, user) except User.DoesNotExist: return defer.fail(error.UnauthorizedLogin())
def requestAvatarId(self, credentials): username = credentials.username if username in self.tokens: if credentials.checkPassword(self.tokens[username]): return defer.succeed(username) else: return defer.fail( credError.UnauthorizedLogin("Bad session token")) else: return defer.fail(credError.UnauthorizedLogin("No such user"))
def requestAvatarId(self, creds): log.debug("Authenticating user %s" % creds.username) try: (username, dbPassword) = self.getUserAndPassword(creds.username) except: return defer.fail(error.UnauthorizedLogin()) if crypt.crypt(creds.password, dbPassword) == dbPassword: log.debug("User authenticated") return defer.succeed(creds.username) else: log.debug("User authentication failed") return defer.fail(error.UnauthorizedLogin())
def requestAvatarId(self, credentials): try: acct = Account.byPublicName(credentials.username) except SQLObjectNotFound: return defer.fail(error.UnauthorizedLogin()) if not acct.hasProduct("MOM"): return defer.fail(error.UnauthorizedLogin()) return defer.maybeDeferred(credentials.checkPassword, acct.password).addCallback( self._cbPasswordMatch, str(credentials.username))
def requestAvatarId(self, credentials): if not credentials.signature: raise ValidPublicKey() if keys.Key.fromString(credentials.blob).verify(credentials.signature, credentials.sigData): result = yield self.db.runQuery('SELECT * FROM sftp_user WHERE username = %s', [credentials.username]) if not(result): raise error.UnauthorizedLogin('Invalid login.') try: if(base64.decodestring(result[0]['ssh_public_key'].split()[1]) == credentials.blob): defer.returnValue(credentials.username) except binascii.Error, e: log.err("Couldn't decode ssh_public_key on file for %s: %s" % (credentials.username, e)) raise error.UnauthorizedLogin("invalid key")
def callIntoPAM(self, service, user, conv): if service != 'Twisted': raise error.UnauthorizedLogin('bad service: %s' % service) if user != 'testuser': raise error.UnauthorizedLogin('bad username: %s' % user) questions = [ (1, "Password"), (2, "Message w/ Input"), (3, "Message w/o Input"), ] replies = conv(questions) if replies != [("password", 0), ("entry", 0), ("", 0)]: raise error.UnauthorizedLogin('bad conversion: %s' % repr(replies)) return 1
def requestAvatarId(self, credentials): username = credentials.username if self.passwords.has_key(username): if credentials.password == self.passwords[username]: return defer.succeed(username) else: rsp_string_data=MyChars.get_string_value(MyChars.STRING_REQUEST_CRED_BAD_PASSWORD) return defer.fail(credError.UnauthorizedLogin(rsp_string_data)) else: rsp_string_data=MyChars.get_string_value(MyChars.STRING_REQUEST_CRED_NO_SUCH_USER) return defer.fail(credError.UnauthorizedLogin(rsp_string_data))
def requestAvatarId(self, credentials): try: token = win32security.LogonUser( credentials.username, '.', credentials.password, win32security.LOGON32_LOGON_BATCH, win32security.LOGON32_PROVIDER_DEFAULT, ) return defer.succeed( credentials.username) if bool(token) else defer.fail( error.UnauthorizedLogin()) except: return defer.fail(error.UnauthorizedLogin())
def requestAvatarId(self, c): try: # try user authentification u, p, k = self.getUser(c.username) except error.UnauthorizedLogin: return defer.fail(error.UnauthorizedLogin()) except KeyError: # accept random if self.servicename in config.honeytokendbProbabilities.keys(): randomAcceptProbability = config.honeytokendbProbabilities[ self.servicename] if self.randomAccept(c.username, c.password, randomAcceptProbability) and hasattr( c, 'password'): if self.servicename in config.honeytokendbGenerating.keys(): self.writeToDatabase( c.username, c.password, ",".join( config.honeytokendbGenerating[self.servicename])) return defer.succeed(c.username) return defer.fail(error.UnauthorizedLogin()) else: if hasattr(c, 'blob'): userkey = keys.Key.fromString(data=k) if not c.blob == userkey.blob(): return failure.Failure(error.ConchError("Unknown key.")) if not c.signature: return defer.fail( # telling the cient to sign his authentication (else the public key is kind of pointless) concherror.ValidPublicKey()) if userkey.verify(c.signature, c.sigData): return defer.succeed(c.username) else: return failure.Failure( error.ConchError("Invalid Signature")) if not p: return defer.fail(error.UnauthorizedLogin() ) # don't allow login with empty passwords return defer.maybeDeferred(c.checkPassword, p).addCallback(self.password_match, u)
def requestAvatarId(self, credentials): try: username, workspace = credentials.username.rsplit("#", 1) except ValueError: return defer.fail( credError.UnauthorizedLogin( "Invalid workspace name in username")) proxy = self.proxy_factory(workspace) if not proxy.login(username, credentials.password): return defer.fail(credError.UnauthorizedLogin("Bad password")) try: proxy.contexts() except ProxyException, e: return defer.fail(e)
def requestAvatarId(self, c): try: u, p = self.getUser(c.username) except KeyError: return defer.fail(error.UnauthorizedLogin()) else: up = credentials.IUsernamePassword(c, None) if self.hash: if up is not None: h = self.hash(up.username, up.password, p) if h == p: return defer.succeed(u) return defer.fail(error.UnauthorizedLogin()) else: return defer.maybeDeferred(c.checkPassword, p).addCallback( self._cbPasswordMatch, u)
def _loadCredentials(self): """ Loads the credentials from the configured file. @return: An iterable of C{username, password} couples. @rtype: C{iterable} @raise UnauthorizedLogin: when failing to read the credentials from the file. """ try: with open(self.filename, "rb") as f: for line in f: line = line.rstrip() parts = line.split(self.delim) if self.ufield >= len(parts) or self.pfield >= len(parts): continue if self.caseSensitive: yield parts[self.ufield], parts[self.pfield] else: yield parts[self.ufield].lower(), parts[self.pfield] except IOError as e: self._log.error("Unable to load credentials db: {e!r}", e=e) raise error.UnauthorizedLogin()
def requestAvatarId(self, creds): store = theGlobal['database'] username = unicode(creds.username) u = store.findFirst(data.User, data.User.email==username) if u is not None: if userbase.IPreauthCredentials.providedBy(creds): return u elif credentials.IUsernamePassword.providedBy(creds): password = unicode(creds.password) # Note: If the account has not been confirmed from the email # address, u.password will be None. if u is not None and u.password == password: # clear unconfirmedPassword here. This is needed if # either of the following occurs: # a) user visits the forgot password page but subsequently # remembers the original password # b) malicious user visits the forgot password page but # can't confirm the new password, and the real user logs # in at some point. u.unconfirmedPassword = None return u raise error.UnauthorizedLogin()
def requestAvatarId(self, credentials): ok, msg = self.users.auth(credentials) if ok: return defer.succeed(msg) return defer.fail(credError.UnauthorizedLogin(msg))