コード例 #1
0
    def __init__(self,
                 uri,
                 dn,
                 password,
                 storage=None,
                 filterstr=None,
                 **kwargs):
        """
        Set up our object by creating a search client, connecting, and binding.
        """

        if storage is not None:
            self.data = shelve.open(storage)
            self.uuid_dn = shelve.open(storage + 'uuid_dn')
            self.dn_attrs = shelve.open(storage + 'dn_attrs')
            self.using_shelve = True
        else:
            self.data = {}
            self.uuid_dn = {}
            self.dn_attrs = {}
            self.using_shelve = False

        self.data['cookie'] = None
        self.present = []
        self.refresh_done = False
        self.filterstr = filterstr

        SimpleLDAPObject.__init__(self, uri, **kwargs)
        self.simple_bind_s(dn, password)
コード例 #2
0
 def ldap_delete_recursive(self, ldap_conn: SimpleLDAPObject, base_dn: str):
     """Delete all objects and its subordinate entries of given base_dn from ldap."""
     l_search = ldap_conn.search_s(base_dn, ldap.SCOPE_ONELEVEL)
     for dn, _ in l_search:
         if not dn == base_dn:
             self.ldap_delete_recursive(self.ldap_conn, dn)
             ldap_conn.delete_s(dn)
コード例 #3
0
 def unbind_s(self):
     """
     In addition to unbinding from LDAP, we need to close the shelf.
     """
     if self.using_shelve is True:
         self.data.close()
         self.uuid_dn.close()
         self.dn_attrs.close()
     SimpleLDAPObject.unbind_s(self)
コード例 #4
0
def ldap_authenticate(ldap_conn: SimpleLDAPObject, user_dn: str, password: str):
    """Validates/binds the provided dn/password with the LDAP sever."""
    try:
        LOG.debug(f"LDAP bind TRY with username: '******'")
        ldap_conn.simple_bind_s(who=user_dn, cred=password)
        LOG.debug(f"LDAP bind SUCCESS with username: '******'")
        return True
    except ldap.INVALID_CREDENTIALS:
        return False
コード例 #5
0
 def __delete_dn(self, ldap_conn: SimpleLDAPObject, dn: str):
     """Delete given DN from ldap."""
     try:
         ldap_conn.delete_s(dn)
     except ldap.NO_SUCH_OBJECT:
         pass
     except Exception as e:
         self.logger.error(f'Failed to delete DN: {dn}\n')
         raise e
コード例 #6
0
 def __delete_dn(ldap_conn: SimpleLDAPObject, dn: str):
     """Delete given DN from ldap."""
     try:
         ldap_conn.delete_s(dn)
     except ldap.NO_SUCH_OBJECT:
         pass
     except Exception as e:
         sys.stderr.write(f'Failed to delete DN: {dn}\n')
         raise e
コード例 #7
0
 def __delete_access_key(ldap_conn: SimpleLDAPObject, userid: str):
   """Delete access key of given s3userid."""
   try:
     access_key = LdapAccountAction.__get_accesskey(ldap_conn, userid)
     ldap_conn.delete_s(f'ak={access_key},ou=accesskeys,dc=s3,dc=seagate,dc=com')
   except ldap.NO_SUCH_OBJECT:
     pass
   except Exception as e:
     sys.stderr.write(f'failed to delete access key of userid: {userid}\n')
     raise e
コード例 #8
0
 def __is_account_present(ldap_conn: SimpleLDAPObject, account_name: str):
   """Checks if account is present in ldap db."""
   try:
     ldap_conn.search_s(f"o={account_name},ou=accounts,dc=s3,dc=seagate,dc=com", ldap.SCOPE_SUBTREE)
   except ldap.NO_SUCH_OBJECT:
     return False
   except Exception as e:
     sys.stderr.write(f'INFO: Failed to find ldap account: {account_name}, error: {str(e)}\n')
     raise e
   return True
コード例 #9
0
def create_user(con: SimpleLDAPObject, dn: str, password: str):
    username = (dn.split(',')[0]).split('=')[1]
    ldap_obj = ((
        ('objectClass', [b'account', b'simpleSecurityObject']),
        ('uid', username.encode()),
        ('userPassword', password.encode()),
    ))
    try:
        con.add_s(dn, ldap_obj)
    except ldap.ALREADY_EXISTS:
        pass
コード例 #10
0
 def __delete_access_key(self, ldap_conn: SimpleLDAPObject, userid: str):
     """Delete access key of given s3userid."""
     try:
         access_key = self.__get_accesskey(ldap_conn, userid)
         ldap_conn.delete_s(
             f'ak={access_key},ou=accesskeys,dc=s3,dc=seagate,dc=com')
     except ldap.NO_SUCH_OBJECT:
         pass
     except Exception as e:
         self.logger.error(
             f'failed to delete access key of userid: {userid}')
         raise e
コード例 #11
0
  def __get_accesskey(ldap_conn: SimpleLDAPObject, s3userid: str) -> str:
    """Get accesskey of the given userid."""
    access_key = None

    from ldap import SCOPE_SUBTREE

    result_list = ldap_conn.search_s('ou=accesskeys,dc=s3,dc=seagate,dc=com',
                                    SCOPE_SUBTREE,
                                    filterstr='(ObjectClass=accessKey)')
    for (_, attr_dict) in result_list:
      if s3userid == attr_dict['s3UserId'][0].decode():
        access_key = attr_dict['ak'][0].decode()
        break
    return access_key
コード例 #12
0
def search_user_by_dn(
    ldap_conn: SimpleLDAPObject,
    user_dn: str = None,
    attrs: Optional[List[str]] = None,
    apply_filter: bool = False,
) -> Optional[Tuple[str, Dict]]:
    try:
        filter_str = _get_ldap_filter() if apply_filter else "(objectClass=*)"
        raw_search_result = ldap_conn.search_s(
            base=user_dn,
            scope=ldap.SCOPE_SUBTREE,
            filterstr=filter_str,
            attrlist=attrs,
        )
    except ldap.NO_SUCH_OBJECT:
        return None
    return _sanitize_ldap_search_results(raw_search_result)
コード例 #13
0
def search_user_by_uid(
    ldap_conn: SimpleLDAPObject,
    uid: str = None,
    attrs: Optional[List[str]] = None,
    apply_filter: bool = False,
) -> Optional[Tuple[str, Dict]]:
    search_filter = (
        f"(&({QuerybookSettings.LDAP_UID_FIELD}={uid})" +
        (_get_ldap_filter() if apply_filter else "(objectClass=*)") + ")")
    try:
        raw_search_result = ldap_conn.search_s(
            base=QuerybookSettings.LDAP_SEARCH,
            scope=ldap.SCOPE_SUBTREE,
            filterstr=search_filter,
            attrlist=attrs,
        )
    except ldap.NO_SUCH_OBJECT:
        return None
    return _sanitize_ldap_search_results(raw_search_result)
コード例 #14
0
ファイル: aciuserdntest.py プロジェクト: rsevilla87/scripts
print "create userb"
dn = "uid=userb,ou=people," + basedn
userbdn = dn
ent = Entry(dn)
ent.setValues('objectclass', ['inetOrgPerson', 'myAuxOc'])
ent.setValues('cn', 'User B')
ent.setValues('sn', 'B')
ent.setValues('givenName', 'User')
userbpw = 'userb'
ent.setValues('userPassword', userbpw)
ent.setValues('owner', useradn)
srv.add_s(ent)

print "create aci to allow usera to set password in userb"
aci = '(targetattr="userPassword")(version 3.0; acl "Owners can set passwords"; allow(write) userattr="owner#USERDN";)'
mod = [(ldap.MOD_REPLACE, 'aci', aci)]
srv.modify_s(basedn, mod)

print "bind as usera"
aconn = SimpleLDAPObject('ldap://%s:%d' % (host1, port1))
aconn.simple_bind_s(useradn, userapw)

print "user a will modify user b userPassword"
userbpw = 'anewpassword'
mod = [(ldap.MOD_REPLACE, 'userPassword', userbpw)]
aconn.modify_s(userbdn, mod)

print "userb will attempt to bind with new password"
bconn = SimpleLDAPObject('ldap://%s:%d' % (host1, port1))
bconn.simple_bind_s(userbdn, userbpw)
コード例 #15
0
def delete_user(con: SimpleLDAPObject, dn: str):
    con.delete_s(dn)
コード例 #16
0
ファイル: ticket48013_test.py プロジェクト: Firstyear/ds
 def __init__(self, uri):
     # Init the ldap connection
     SimpleLDAPObject.__init__(self, uri)
コード例 #17
0
ファイル: bug551198.py プロジェクト: axdxnco/scripts
import tempfile
from ldap.ldapobject import SimpleLDAPObject
import pprint

host1 = "localhost.localdomain"
port1 = 1110
basedn = 'dc=example,dc=com'

ldapifilepath = os.environ.get('PREFIX', "") + "/var/run/slapd-srv.socket"

os.environ['USE_GDB'] = "1"
srv = DSAdmin.createInstance({
	'newrootpw': 'password',
	'newhost': host1,
	'newport': port1,
	'newinst': 'srv',
	'newsuffix': basedn,
    'no_admin': True,
    'ldapifilepath': ldapifilepath
})
del os.environ['USE_GDB']

ldapiurl = ldapurl.LDAPUrl(None, "ldapi", ldapifilepath)

conn = SimpleLDAPObject(ldapiurl.initializeUrl())
print "connecting to", ldapiurl.initializeUrl()

conn.simple_bind_s("cn=directory manager", "password")
ents = conn.search_s("", ldap.SCOPE_BASE)
pprint.pprint(ents)
コード例 #18
0
from dsadmin import DSAdmin, Entry
from ldap.ldapobject import SimpleLDAPObject
import pprint

host1 = "localhost.localdomain"
port1 = 1110
basedn = 'dc=example,dc=com'

ldapifilepath = os.environ.get('PREFIX', "") + "/var/run/slapd-srv.socket"

os.environ['USE_GDB'] = "1"
srv = DSAdmin.createInstance({
    'newrootpw': 'password',
    'newhost': host1,
    'newport': port1,
    'newinst': 'srv',
    'newsuffix': basedn,
    'no_admin': True,
    'ldapifilepath': ldapifilepath
})
del os.environ['USE_GDB']

ldapiurl = ldapurl.LDAPUrl(None, "ldapi", ldapifilepath)

conn = SimpleLDAPObject(ldapiurl.initializeUrl())
print "connecting to", ldapiurl.initializeUrl()

conn.simple_bind_s("cn=directory manager", "password")
ents = conn.search_s("", ldap.SCOPE_BASE)
pprint.pprint(ents)
コード例 #19
0
 def cancel(self):
     """
     A simple wrapper to call parent class with syncrepl search ID.
     """
     SimpleLDAPObject.cancel(self, self.search_id)
コード例 #20
0
ファイル: acctpolicy.py プロジェクト: taraksinha/scripts
       (ldap.MOD_REPLACE, 'altstateattrname', 'createTimestamp'),
       (ldap.MOD_REPLACE, 'specattrname', 'acctPolicySubentry'),
       (ldap.MOD_REPLACE, 'limitattrname', 'accountInactivityLimit')]
srv.modify_s('cn=config,cn=Account Policy Plugin,cn=plugins,cn=config', mod)

print "restart server for changes to take effect"
srv.stop()
srv.start()

print "find scarter"
ents = srv.search_s(basedn, ldap.SCOPE_SUBTREE, 'uid=scarter', ['lastLoginTime', 'createTimestamp'])
userdn = ents[0].dn
pprint.pprint(ents[0])

print "bind as", userdn
conn = SimpleLDAPObject('ldap://%s:%d' % (host1, port1))
try:
    conn.simple_bind_s(userdn, 'sprain')
except ldap.CONSTRAINT_VIOLATION:
    print "user is prevented from logging in after", inactivetime, "seconds of inactivity"
    ents = srv.search_s(basedn, ldap.SCOPE_SUBTREE, 'uid=scarter', ['lastLoginTime', 'createTimestamp'])
    print "lastLoginTime:", ents[0].lastLoginTime

print "sleep for a while . . ."
time.sleep(inactivetime)
print "bind as", userdn, "again - see if there is any account policy"
conn = SimpleLDAPObject('ldap://%s:%d' % (host1, port1))
try:
    conn.simple_bind_s(userdn, 'sprain')
except ldap.CONSTRAINT_VIOLATION:
    print "user is prevented from logging in after", inactivetime, "seconds of inactivity"
コード例 #21
0
 def __init__(self, uri):
     # Init the ldap connection
     SimpleLDAPObject.__init__(self, uri)