TL;DR
This guide shows you how to authenticate an Active Directory (AD) user over a TCP socket connection using Python. It covers setting up the necessary libraries, establishing a secure connection, sending credentials, and verifying the authentication response.
Prerequisites
- Python 3.6 or higher
- The
pywinrmlibrary (for Windows AD) – install with:pip install pywinrm - Basic understanding of TCP sockets and Active Directory concepts.
Steps
- Import Necessary Libraries
- Establish a TCP Socket Connection
- Configure pywinrm Session
- Send Username to the Server
- Receive Password Request (Optional)
- Send Password to the Server
- Receive Authentication Response
- Verify Authentication
- If
response == "Success", authentication succeeded. - Otherwise, handle the failure appropriately (e.g., log an error message).
- Close the Socket Connection
- Security: This example transmits credentials in plain text over a TCP socket, which is highly insecure. Always use TLS/SSL to encrypt the connection for production environments.
- Error Handling: Implement robust error handling to catch potential exceptions (e.g., network errors, authentication failures).
- Server Implementation: The server-side code needs to be implemented to handle the socket connection, receive credentials, authenticate against AD, and send an appropriate response.
- pywinrm Alternatives: For more complex scenarios or cross-platform compatibility, consider using other libraries like
sshtunnelfor secure connections.
Start by importing the required libraries:
import socket
import pywinrm
Create a TCP socket and connect to your AD server. Replace 'your_ad_server_ip' with the actual IP address and 12345 with your chosen port number.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('your_ad_server_ip', 12345))
print("Connected to AD server")
Configure a pywinrm session for authentication. Replace placeholders with your AD credentials and server details.
session = pywinrm.Session('your_ad_server_ip', auth=('username', 'password'))
Encode the username as bytes and send it over the socket:
username = "testuser".encode('utf-8')
sock.sendall(username)
If your server requires a password prompt, receive the request and handle it accordingly. This step is omitted if using pre-configured credentials.
Encode the password as bytes and send it over the socket:
password = "mypassword".encode('utf-8')
sock.sendall(password)
Receive the authentication response from the server.
response = sock.recv(1024).decode('utf-8')
print("Authentication response:", response)
Check the received response to determine if authentication was successful. The exact format of the response will depend on your server implementation.
Close the socket connection when finished:
sock.close()
print("Socket closed")

