LDAP is a LIGHTWEIGHT DIRECTORY ACCESS PROTOCOL. It is an internet protocol that works on TCP/IP, and it is used to access/fetch the information from the directories. All the directories are not preferable; it is usually used to access those directories that are active.
Features/characteristics of LDAP
LDAP is known to be a functional model; it is simple and unique because of its ability to avoid the duplication of data to keep the content safe and coherent. Some of the major characteristics of LDAP are as follows.
- LDAP is known to be an open-source implementation protocol and can be downloaded free from the internet.
- It has an important feature dealing with data security. As it supports transport layer security (TLS), sensitive data can be easily secured from the snatchers.
- LDAP is also beneficial in supporting the database systems. As it stores directories and allows the user to choose the database according to the server information.
LDAP has many functions regarding the services it provides. We will highlight some of them here.
For Authentication of the client
As LDAP is easily accessible and forms many operations to connect/disconnect to/from an LDAP server, it causes the rights on the access and protects the private information. It authenticates the clients who pass the connectivity request so that only the authentic and valid user can be connected. For the authentication process, a client session is created and ended by using the functions. Like BIND/UNBIND, Abandon.
For the query of information
It includes comparison and search functions that are used to fetch the information from the directory. In this situation, a server plays an important role, as it performs many actions by following the functions like search, Compare Entry.
Modification of the data
Modification of data comprises addition, deletion, and modification of the stored data in the specified directory. The main functions include.
1. Add an entry.
2. Delete the entry of data.
3. Modification of the data.
This modification is at both ends. For instance, the client establishes a session with the server by using the hostname and the port number at the client side. For security purposes, the user uses the IDs and the passwords for the authentication. Whereas at the server-side, the server is capable of reading, updating, and searching the data.
LDAP interaction between the client and server
It is similar to any of the simple client-server interactions. In this case, the client uses the protocol functions against the server. The below points explain this interaction briefly.
- A client sends a protocol request to the server.
- The server performs different operations on the directory like search etc.
- The response of the server is sent back to the client.
Several software’s can easily create a connection and make an LDAP server. But all of them require directories. If the user is unwilling to install the directory server on the system but wants to use LDAP, then the user can use four11, bigfoot, etc. The creation of the LDAP client is simple as there are SDK in many other languages like C++, Java, etc. To be an LDAP client, the user needs to perform some tasks.
- For your programming language, go get an SDK.
- Use the function of SDK for the creation of LDAP.
- After these steps, now perform operations on LDAP.
Creation of LDAP user
Now, we will create an LDAP user by using the script in Python language. A CSV file is used. After creation, the script can be further modified according to the requirements, like adding a click library that creates individual users.
Step 1: install the requirements
The first step is to install the prerequisites for user creation. This involves the installation of “python-ldap”.
Step 2: Using Python form a connection with LDAP
This step is to build a connection with the LDAP. Firstly, import ldap, sys, and LDAP_ADMIN_DN modules from the python library. Then we will define a function that carries host and password as an argument of a function.
The main function is written inside the body of the ‘try’ part of exceptional handling. This will eliminate the occurrence of any big issue, and if any minute error occurs, an exception request is thrown, which is solved by the catch () method. This is not described here.
Moving back towards the code, the connection is built by using the below-written line.
import sys
import LDAP_ADMIN_DN
def try_ldap_bind(ldap_host, admin_pass):
try:
ldap_conn = ldap.initialize(ldap_host)
except ldap.SERVER_DOWN:
print("Can't contact LDAP server")
exit(4)
try:
ldap_conn.simple_bind_s(LDAP_ADMIN_DN, admin_pass)
except (ldap.INVALID_CREDENTIALS):
print("This password is incorrect!")
sys.exit(3)
print("Authentization successful")
If the password or the hostname is not correct, a message is displayed that the password is not correct. Otherwise, it shows a message that the Authentication is successful in the case of correct credentials.
Step 3: CSV file Loading
After importing the CSV module, we will take an empty array. To open the already created CSV file, here open() function command is used. The file is opened by using an object. That object and both the files are passed as parameters of the open function (). Each line in the code is considered line by line through the reader function.
All the values are entered into the array by using a FOR loop. Each word is placed at every index of an array. For example, the first word is the username; it is placed at the zero indexes of that array. A similar process is used for all the indexes. These words are present in the ‘user’ variable. Now, these are appended with the ‘users_to_import’ array through the append function.
That’s how the data present in the CSV file is loaded now.
users_to_import = []
with open('file.csv', 'rb') as users_csv_file:
users_reader = csv.reader(users_csv_file)
for row in users_reader:
user = {
'username': row[0],
'password': row[1],
'firstname': row[2],
'Lastname': row[3],
'group': row[4],
'shell': row[5],
'hosts': row[6],
}
users_to_import.append(user)
Step 4: User creation on LDAP server
From the CSV file, we will create a user using a function. The first step deals with defining a function named ‘create_user’. For example, the case of the group we have:
dn = 'uid=' + user['username'] + ', ' + LDAP_BASE_DN
fullname = user['firstname'] + + user['lastname']
home_dir = HOME_BASE + '/' + user['username']
gid = find_gid(user['group'])
lastchange = int(math.floor(time() / 86400))
It takes the user name and the password of the admin. Inside the function body, each field of the user creation form is filled with the piece of information it gets. This information is stored in the variables. These variables are used while assigning the values in the array. In the end, we use the append function to bind the values. Here an if-statement is used. This will check the length of the ‘user’ array through the len().
# entry.append( ('host', user['hosts']) )
entry.extend([
('objectClass', ["person", "organizationalPerson",
"inetOrgPerson", "posixAccount", "top", "shadowAccount", "hostObject"]), ('uid', user['username']),
('cn', fullname),
('givenname', user['firstname']),
('sn', user['Lastname']),
('mail', user['email']),
('uidNumber', str(user['uid'])),
('gidNumber', str(gid)),
('loginShell', user['shell']),
('homeDirectory', home_dir),
('shadowMax', "99999"),
('shadowwarning', "7"),
('shadowLastChange', str(lastchange)), ('userPassword', user['password'])
])
if (len(user['hosts'])):
entry.append(('host', user['hosts']))
The same process of array declaration is used here. Each index of the array contains the value from the content present in the CSV file. This time, each index number is also given the variable name that we have used in the function above.
Now moving towards the last phase of user creation, here we will build a connection when the user is created by assigning each value of the array. Again use a try body to ignore errors. In the end, we will use the unbind function to close the connection.
ldap_conn.simple_bind_s(LDAP_ADMIN_DN, admin_pass)
try:
ldap_conn.add_s(dn, entry)
finally:
ldap_conn.unbind_s()
Conclusion
‘Python LDAP example’ aims to provide the LDAP protocol’s features, functions, and user creation function. We have briefly explained this protocol’s important aspects by highlighting the interaction between server and client. We are hopeful that this tutorial will be beneficial for the user regarding LDAP implementation in the Python language.