def CollectADComputers(Domain_target): server = ldap3.Server('{}BNADCRW01.{}'.format(Domain_target, dictFOREST[Domain_target]), use_ssl=True, get_info=ldap3.ALL) conn = ldap3.Connection( server, auto_bind=True, user="", #LDAP User password="", #LDAP Password authentication=ldap3.NTLM, check_names=True) if not conn.bind(): print('error in bind', conn.result) #print(conn.extend.standard.who_am_i()) #print(conn) ADBase = 'DC={},DC=nucorsteel,DC=local'.format(Domain_target) ADUsers = ldap3.ObjectDef('User', conn) print(ADBase) print('\n') ADQuery = '(|(cn=*IT*all)(cn=*ADMIN*)(cn=IT*)(cn=*IT))(!(cn=*Admin Account*))' ADReader = ldap3.Reader(conn, ADUsers, ADBase, ADQuery) ADReader.search_subtree() with open( 'C:\\Users\\patrick.roland\\Documents\\new_adminList{}.csv'.format( Domain_target), 'w') as txtfile: #where the txtfile needs to land for x in range(0, len(ADReader)): txtfile.write( str(ADReader[x].cn) + ',' + str(ADReader[x].description) + ',' + str(ADReader[x].name) + ',' + str(ADReader[x].mail) + '\n') '''
def CollectADComputers(Domain_target): server = ldap3.Server('{}BNADCRW01.{}'.format(Domain_target, dictFOREST[Domain_target]), use_ssl=True, get_info=ldap3.ALL) conn = ldap3.Connection( server, auto_bind=True, user="", #LDAP username password="", #LDAP password authentication=ldap3.NTLM, check_names=True) if not conn.bind(): print('error in bind', conn.result) #print(conn.extend.standard.who_am_i()) #print(conn) ADBase = 'DC={},DC=nucorsteel,DC=local'.format(Domain_target) ADComps = ldap3.ObjectDef('computer', conn) print(ADBase) print('\n') ADQuery = '(sAMAccountType=805306369)' ADReader = ldap3.Reader(conn, ADComps, ADBase, ADQuery) ADReader.search() with open( 'C:\\Users\\patrick.roland\\Documents\\MachineList{}.csv'.format( Domain_target), 'w') as txtfile: for x in range(0, len(ADReader)): txtfile.write( str(ADReader[x].whenCreated) + ',' + str(ADReader[x].cn) + ',' + str(ADReader[x].objectGUID) + ',' + str(ADReader[x].lastLogon) + ',' + str(ADReader[x].operatingSystem) + ',' + str(ADReader[x].whenCreated) + '\n') '''
def _get_user_dn_and_attributes( user_ldap_uid: str, attributes: typing.Sequence[str] = () ) -> typing.Optional[typing.Sequence[typing.Any]]: ldap_host = flask.current_app.config['LDAP_SERVER'] user_base_dn = flask.current_app.config['LDAP_USER_BASE_DN'] uid_filter = flask.current_app.config['LDAP_UID_FILTER'] object_def = flask.current_app.config['LDAP_OBJECT_DEF'] user_dn = flask.current_app.config['LDAP_USER_DN'] password = flask.current_app.config['LDAP_PASSWORD'] server = ldap3.Server(ldap_host, use_ssl=True, get_info=ldap3.ALL) try: connection = ldap3.Connection(server, user=user_dn, password=password, auto_bind=True) object_def = ldap3.ObjectDef(object_def, connection) reader = ldap3.Reader(connection, object_def, user_base_dn, uid_filter.format(user_ldap_uid)) reader.search(attributes) # search if uid matches exactly one user, not more if len(reader) != 1: return None user_attributes = [reader[0].entry_dn] for attribute in attributes: value = getattr(reader[0], attribute, None) if value: user_attributes.append(value[0]) else: user_attributes.append(None) return user_attributes except ldap3.core.exceptions.LDAPException: return None
def alterRefreshTokens(server_uri, bind_dn, pw, new_scope, tokenOU): # Creating a Server object server = ldap3.Server(server_uri) # Creating a Connection context to connect to the Server with service account credentials with ldap3.Connection(server, user=bind_dn, password=pw, auto_bind=True) as conn: # Creating an ObjectDef object to represent frCoreToken objectClass obj_frCoreToken = ldap3.ObjectDef('frCoreToken', conn) # Creating a Reader object to read LDAP objects in the token organisationalUnit r = ldap3.Reader(conn, obj_frCoreToken, tokenOU) print(r) print(r.search()) # Creating a Writer object fron the Reader to be able to edit LDAP entries w = ldap3.Writer.from_cursor(r) print(w) for index, entry in enumerate(r): # Gathering the coreTokenObject field from the current entry coreTokenObject = entry.entry_attributes_as_dict['coreTokenObject'] # Checking that the coreTokenObject field (list) is not empty if (coreTokenObject): # Reading the coreTokenObject field as a JSON (string to JSON) coreTokenObject_json = json.loads( entry.entry_attributes_as_dict['coreTokenObject'][0]) # Reading the scopes field of the coreTokenObject scopes_list = coreTokenObject_json['scope'] # Checking whether the new scope is already in the coreTokenObject if new_scope not in scopes_list: print("testScope missing in index = " + str(index)) print(type(coreTokenObject_json['scope'])) # Adding the new scope to the JSON object coreTokenObject_json['scope'].append(new_scope) print("coreTokenObject_json['scope'] = " + str(coreTokenObject_json['scope'])) # Creating a new string to update the coreTokenObject new_coreTokenObject = json.dumps( coreTokenObject_json ) #TODO : Possible bug : Remove spaces from the JSON # Creating a new string to update the coreTokenString01 from the coreTokenObject scopes new_coreTokenString01 = ",".join( coreTokenObject_json['scope']) print("new_coreTokenObject = " + new_coreTokenObject) # Adding coreTokenObject update to the Writer w[index].coreTokenObject = new_coreTokenObject # Adding coreTokenString01 update to the Writer w[index].coreTokenString01 = new_coreTokenString01 print(w[index]) # Commiting changes to the CTS LDAP w.commit()
import ldap3 server = ldap3.Server('<DC-IP>',get_info=ldap3.ALL) person = ldap3.ObjectDef('inetOrgPerson') conn = ldap3.Connection(server, user="******", password="******", authentication=ldap3.NTLM) conn.bind() result = conn.delete('cn=USERNAMETODELETE,cn=Users,dc=EXAMPLE,dc=ORG') print("user was deleted: {}".format(result) conn.unbind()
async def get(self): """ Cheks wether the user is logged in or not and handles authentication """ if not self.OAUTH_CLIENT_ID: self.set_secure_cookie("user", "anonymous-email") self.set_secure_cookie("user_name", "anonymous") self.set_secure_cookie("is_admin", "on") return self.redirect("/dashboard") if self.get_argument("code", ""): user_data = await self.get_authenticated_user( self.get_argument("code", "")) # Use user_data to find the user in your user database or use their data directly email = user_data["email"] uid = user_data["username"] self.set_secure_cookie("user", email) self.set_secure_cookie("user_name", uid) # Skip LDAP authorization checking if not defined -> all users are allowed if "LDAP_DEFAULT_SERVER" not in os.environ: self.set_secure_cookie("is_admin", "on") else: # Connect to ldap to check access of group try: if 'LDAP_FALLBACK_SERVER' in os.environ: pool = [ ldap3.Server(os.environ['LDAP_DEFAULT_SERVER'], use_ssl=True, get_info=ldap3.ALL), ldap3.Server(os.environ['LDAP_FALLBACK_SERVER'], use_ssl=True, get_info=ldap3.ALL) ] else: pool = ldap3.Server(os.environ['LDAP_DEFAULT_SERVER'], use_ssl=True, get_info=ldap3.ALL) base_dn = os.environ['LDAP_BASE_DN'] user_dn = os.environ['LDAP_USER_DN'] password = os.environ['LDAP_PASSWORD'] connection = ldap3.Connection(pool, user=user_dn, password=password, auto_bind=True) reader = ldap3.Reader( connection, ldap3.ObjectDef('inetUser', connection), base_dn, '(&(objectClass=inetOrgPerson)(mail={email})(uid={uid}))' .format(email=email, uid=uid)) user_infos = reader.search() self.set_secure_cookie("is_admin", "off") if user_infos: for user in user_infos: if 'memberOf' in user: if os.environ['LDAP_GROUP_DN'] in user[ 'memberOf']: self.set_secure_cookie("is_admin", "on") break else: print("Error") # TODO Error handling except Exception as e: print(e) return self.redirect("/dashboard") if self.get_argument("error", ""): self.write(self.get_argument("error", "")) else: return self.authorize_redirect( redirect_uri=self.OAUTH_REDIRECT_URI, client_id=self.OAUTH_CLIENT_ID, client_secret=self.OAUTH_CLIENT_SECRET, scope=["api"], response_type="code", )
# Service account credentials bind_dn = "cn=Directory Manager" pw = "Admin001" # Scope to be added new_scope = "TestScope" # Attributes to be gathered attrs = ["coreTokenObject", "coreTokenString01"] # organisationalUnit where the tokens can be found tokenOU = "ou=famrecords,ou=openam-session,ou=tokens,dc=openam,dc=forgerock,dc=org" # Creating a Server object server = ldap3.Server(server_uri) # Creating a Connection context to connect to the Server with service account credentials with ldap3.Connection(server, user=bind_dn, password=pw, auto_bind=True) as conn: # Creating an ObjectDef object to represent frCoreToken objectClass obj_frCoreToken = ldap3.ObjectDef('frCoreToken', conn) # Creating a Reader object to read LDAP objects in the token organisationalUnit r = ldap3.Reader(conn, obj_frCoreToken, tokenOU) print(r) print(r.search()) # Creating a Writer object fron the Reader to be able to edit LDAP entries w = ldap3.Writer.from_cursor(r) print(w) for index, entry in enumerate(r): # Gathering the coreTokenObject field from the current entry coreTokenObject = entry.entry_attributes_as_dict['coreTokenObject'] # Checking that the coreTokenObject field (list) is not empty if(coreTokenObject): # Reading the coreTokenObject field as a JSON (string to JSON) coreTokenObject_json = json.loads(entry.entry_attributes_as_dict['coreTokenObject'][0]) # Reading the scopes field of the coreTokenObject