def add_sshpubkey(self, username, sshpubkey):
"""
Add an sshPublicKey attribute to the user's dn
"""
dn = 'uid={0},{1}'.format(username, self.base_dn)
try:
with self._ldap_connection() as ldap_cxn:
ldap_cxn.simple_bind_s(self.bind_dn, self.bind_pw)
mod_list = [(ldap.MOD_ADD, 'sshPublicKey', str(sshpubkey))]
ldap_cxn.modify_s(dn, mod_list)
except (ldap.INVALID_CREDENTIALS, ldap.INSUFFICIENT_ACCESS, ldap.LDAPError) as e:
self.bus.log('LDAP Error: {0}'.format(e.message['desc'] if 'desc' in e.message else str(e)),
level=40,
traceback=True)
raise
python类INVALID_CREDENTIALS的实例源码
def auth(self, username, password):
"""
Authenticate a user against the ldap server
"""
dn = 'uid={0},{1}'.format(username, self.base_dn)
try:
with self._ldap_connection() as ldap_cxn:
ldap_cxn.simple_bind_s(dn, password)
return True
except ldap.INVALID_CREDENTIALS:
raise
except ldap.INVALID_DN_SYNTAX:
self.bus.log('Invalid DN syntax in configuration: {0}'.format(self.base_dn), 40)
raise
except ldap.LDAPError as e:
self.bus.log('LDAP Error: {0}'.format(e.message['desc'] if 'desc' in e.message else str(e)),
level=40,
traceback=True)
raise
def delete_sshpubkey(self, username, sshpubkey):
"""
Add an sshPublicKey attribute to the user's dn
"""
dn = 'uid={0},{1}'.format(username, self.base_dn)
try:
with self._ldap_connection() as ldap_cxn:
ldap_cxn.simple_bind_s(self.bind_dn, self.bind_pw)
mod_list = [(ldap.MOD_DELETE, 'sshPublicKey', str(sshpubkey))]
ldap_cxn.modify_s(dn, mod_list)
except (ldap.INVALID_CREDENTIALS, ldap.INSUFFICIENT_ACCESS, ldap.LDAPError) as e:
self.bus.log('LDAP Error: {0}'.format(e.message['desc'] if 'desc' in e.message else str(e)),
level=40,
traceback=True)
raise
def ldapAuthenticate(username, password):
if settings.AUTH_LDAP_SERVER_URI is None:
return False
if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
return False
try:
connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
connection.protocol_version = ldap.VERSION3
user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
connection.simple_bind_s(user_dn, password)
return True
except ldap.INVALID_CREDENTIALS:
return False
except ldap.SERVER_DOWN:
return False
def ldapAuthenticate(username, password):
if settings.AUTH_LDAP_SERVER_URI is None:
return False
if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
return False
try:
connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
connection.protocol_version = ldap.VERSION3
user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
connection.simple_bind_s(user_dn, password)
return True
except ldap.INVALID_CREDENTIALS:
return False
except ldap.SERVER_DOWN:
return False
def ldapAuthenticate(username, password):
if settings.AUTH_LDAP_SERVER_URI is None:
return False
if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
return False
try:
connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
connection.protocol_version = ldap.VERSION3
user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
connection.simple_bind_s(user_dn, password)
return True
except ldap.INVALID_CREDENTIALS:
return False
except ldap.SERVER_DOWN:
# TODO: Return error instead of none
return False
def ldapAuthenticate(username, password):
if settings.AUTH_LDAP_SERVER_URI is None:
return False
if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
return False
try:
connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
connection.protocol_version = ldap.VERSION3
user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
connection.simple_bind_s(user_dn, password)
return True
except ldap.INVALID_CREDENTIALS:
return False
except ldap.SERVER_DOWN:
return False
def check_credentials(self, username, password):
try:
ldap_client = ldap.initialize(self.config["server"])
ldap_client.set_option(ldap.OPT_REFERRALS,0)
ldap_client.simple_bind_s("uid=%s,%s" % (username, self.config["memberdn"]), password)
except ldap.INVALID_DN_SYNTAX:
ldap_client.unbind()
return False
except ldap.INVALID_CREDENTIALS:
ldap_client.unbind()
return False
except ldap.UNWILLING_TO_PERFORM:
ldap_client.unbind()
return False
except ldap.SERVER_DOWN:
ldap_client.unbind()
raise ServerDownException()
return False
ldap_client.unbind()
return True
def ldap_bind_with_user(module, conn, username, password):
result = False
try:
conn.simple_bind_s(username, password)
result = True
except ldap.INVALID_CREDENTIALS:
fail_msg = "Invalid Credentials for user {}".format(username)
module.fail_json(msg=fail_msg)
except ldap.LDAPError as e:
fail_msg = "LDAP Error Binding user: {}: ERROR: {}".format(username, ldap_errors(e))
module.fail_json(msg=fail_msg)
return result
def set_password(self, username, hashes):
"""
Administratively set the user's password using the given hashes.
"""
dn = 'uid={0},{1}'.format(username, self.base_dn)
try:
with self._ldap_connection() as ldap_cxn:
ldap_cxn.simple_bind_s(self.bind_dn, self.bind_pw)
mod_nt = (ldap.MOD_REPLACE, 'sambaNTPassword', hashes['sambaNTPassword'])
mod_ssha = (ldap.MOD_REPLACE, 'userPassword', hashes['userPassword'])
mod_list = [mod_nt, mod_ssha]
ldap_cxn.modify_s(dn, mod_list)
except ldap.INVALID_CREDENTIALS:
self.bus.log('Invalid credentials for admin user: {0}'.format(self.bind_dn), 40)
raise
except ldap.INSUFFICIENT_ACCESS:
self.bus.log('Insufficient access for admin user: {0}'.format(self.bind_dn), 40)
raise
except ldap.INVALID_DN_SYNTAX:
self.bus.log('Invalid DN syntax in configuration: {0}'.format(self.base_dn), 40)
raise
except ldap.LDAPError as e:
self.bus.log('LDAP Error: {0}'.format(e.message['desc'] if 'desc' in e.message else str(e)),
level=40,
traceback=True)
raise
def change_password(self, username, oldpassword, hashes):
"""
Change the user's password using their own credentials.
"""
dn = 'uid={0},{1}'.format(username, self.base_dn)
try:
with self._ldap_connection() as ldap_cxn:
ldap_cxn.simple_bind_s(dn, oldpassword)
# don't use LDAPObject.passwd_s() here to make use of
# ldap's atomic operations. IOW, don't change one password
# but not the other.
mod_nt = (ldap.MOD_REPLACE, 'sambaNTPassword', hashes['sambaNTPassword'])
mod_ssha = (ldap.MOD_REPLACE, 'userPassword', hashes['userPassword'])
mod_list = [mod_nt, mod_ssha]
ldap_cxn.modify_s(dn, mod_list)
except ldap.INVALID_CREDENTIALS:
raise
except ldap.INVALID_DN_SYNTAX:
self.bus.log('Invalid DN syntax in configuration: {0}'.format(self.base_dn), 40)
raise
except ldap.LDAPError as e:
self.bus.log('LDAP Error: {0}'.format(e.message['desc'] if 'desc' in e.message else str(e)),
level=40,
traceback=True)
raise
def __init__(self, uri, cn, dc, secret):
self.conn = None
self.uri = uri
self.dc = dc
self.secret = secret
try:
self.conn = ldap.initialize(self.uri)
self.conn.protocol_version = ldap.VERSION3
self.conn.simple_bind_s(cn+","+self.dc,self.secret)
print("Connection established.")
except ldap.INVALID_CREDENTIALS:
print("Your username or password is incorrect.")
sys.exit()
except ldap.LDAPError as e:
if type(e.message) == dict and e.message.has_key('desc'):
print(e.message['desc'])
else: print(e)
sys.exit()
def test_returns_none_if_user_password_mismatch(self):
self.request.registry.ldap_cm.connection \
.return_value.__enter__.side_effect = [self.conn, ldap.INVALID_CREDENTIALS()]
self.assertIsNone(self.policy.authenticated_userid(self.request))
def ldap_auth(self, username, password):
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.cert_path)
connection = ldap.initialize(self.ldap_url)
connection.set_option(ldap.OPT_REFERRALS, 0)
try:
if password:
connection.simple_bind_s(username + self.user_suffix, password)
else:
return False
except ldap.INVALID_CREDENTIALS:
return False
except ldap.SERVER_DOWN:
return None
return True
def test_failure_authentication(self):
session = pyldap_orm.LDAPSession(backend='ldap://localhost:9389')
with pytest.raises(ldap.INVALID_CREDENTIALS):
session.authenticate('cn=ldapmanager,ou=Services,ou=People,dc=example,dc=com',
'invalid')
pyAuthenticationByLDAP.py 文件源码
项目:LinuxBashShellScriptForOps
作者: DingGuodong
项目源码
文件源码
阅读 34
收藏 0
点赞 0
评论 0
def __init__(self, username, password):
ldap_host = "192.168.78.8"
ldap_port = "389"
ldaps_port = "636"
ldap_enable_ldaps = False
self.ldap_base_dn = "DC=example,DC=com,DC=cn" # example.com.cn
self.ldap_user = username
self.ldap_password = password
if ldap_enable_ldaps is True:
self.uri = "ldaps://" + ldap_host + ":" + ldaps_port
else:
self.uri = "ldap://" + ldap_host + ":" + ldap_port
self.is_active = False
self.user_data = None
self.conn = ldap.initialize(self.uri)
try:
self.conn.set_option(ldap.OPT_REFERRALS, 0) # this option is required in Windows Server 2012
self.conn.simple_bind_s(who=self.ldap_user, cred=self.ldap_password)
except ldap.INVALID_CREDENTIALS:
raise Exception("Invalid credentials")
except ldap.SERVER_DOWN:
raise Exception("Can't contact LDAP server")
self.is_active = True
self.user_data = self.conn.search_s(self.ldap_base_dn, ldap.SCOPE_SUBTREE,
'userPrincipalName=' + self.ldap_user)
# self.user_data = self.conn.search_s(self.ldap_base_dn, ldap.SCOPE_SUBTREE)
self.conn.unbind()
def do_bind(self):
try:
self.con.simple_bind_s(self.username, self.password)
self.is_binded = True
return True
except ldap.INVALID_CREDENTIALS:
print "[!] Error: invalid credentials"
sys.exit(1)
except ldap.LDAPError, e:
print "[!] {}".format(e)
sys.exit(1)
def authenticate(login, password):
"""
Attempt to authenticate the login name with password against the
configured LDAP server. If the user is authenticated, required
group memberships are also verified.
"""
lconn = open_ldap()
server = _config.get('ldap', 'server')
user = LDAPUser(login, lconn)
# Bind to user using the supplied password
try:
user.bind(password)
except (ldap.SERVER_DOWN, ldap.CONNECT_ERROR):
_logger.exception("LDAP server is down")
raise NoAnswerError(server)
except ldap.INVALID_CREDENTIALS:
_logger.warning("Server %s reported invalid credentials for user %s",
server, login)
return False
except ldap.TIMEOUT as error:
_logger.error("Timed out waiting for LDAP bind operation")
raise TimeoutError(error)
except ldap.LDAPError:
_logger.exception("An LDAP error occurred when authenticating user %s "
"against server %s", login, server)
return False
except UserNotFound:
_logger.exception("Username %s was not found in the LDAP catalog %s",
login, server)
return False
_logger.debug("LDAP authenticated user %s", login)
# If successful so far, verify required group memberships before
# the final verdict is made
group_dn = _config.get('ldap', 'require_group')
if group_dn:
if user.is_group_member(group_dn):
_logger.info("%s is verified to be a member of %s",
login, group_dn)
return user
else:
_logger.warning("Could NOT verify %s as a member of %s",
login, group_dn)
return False
# If no group matching was needed, we are already authenticated,
# so return that.
return user
def __init__(self, fqdn, binddn, bindpw):
self._log = logging.getLogger()
self._log.debug('Initialising FreeIPA server %s' % fqdn)
self.fqdn = fqdn
self.hostname_short = fqdn.partition('.')[0]
self._domain = fqdn.partition('.')[2]
self._binddn = binddn
self._bindpw = bindpw
self._url = 'ldaps://' + fqdn
self._base_dn = 'dc=' + fqdn.partition('.')[2].replace('.', ',dc=')
self._active_user_base = 'cn=users,cn=accounts,' + self._base_dn
self._stage_user_base = 'cn=staged users,cn=accounts,cn=provisioning,' + self._base_dn
self._preserved_user_base = 'cn=deleted users,cn=accounts,cn=provisioning,' + self._base_dn
self._groups_base = 'cn=groups,cn=accounts,' + self._base_dn
try:
self._conn = ldap.initialize(self._url)
self._conn.set_option(ldap.OPT_NETWORK_TIMEOUT, 3)
self._conn.simple_bind_s(self._binddn, self._bindpw)
except (
ldap.SERVER_DOWN,
ldap.NO_SUCH_OBJECT,
ldap.INVALID_CREDENTIALS
) as err:
self._log.critical('Bind error: %s (%s)' % (err.message['desc'], self.fqdn))
exit(1)
self.users = self._count_users(user_base='active')
self.ustage = self._count_users(user_base='stage')
self.upres = self._count_users(user_base='preserved')
self.ugroups = self._count_groups()
self.hosts = self._count_hosts()
self.hgroups = self._count_hostgroups()
self.hbac = self._count_hbac_rules()
self.sudo = self._count_sudo_rules()
self.zones = self._count_dns_zones()
self.certs = self._count_certificates()
self.ldap = self._ldap_conflicts()
self.ghosts = self._ghost_replicas()
self.bind = self._anon_bind()
self.msdcs = self._ms_adtrust()
self.replica, self.healthy_agreements = self._replication_agreements()