phi/src/phi/ldap/connection.py

70 lines
2.0 KiB
Python
Raw Normal View History

2017-12-16 23:03:03 +01:00
from ssl import CERT_REQUIRED, PROTOCOL_TLSv1_2
from ldap3 import Tls, Server, Connection, ASYNC
from phi.logging import get_logger
log = get_logger(__name__)
2020-11-20 12:04:17 +01:00
def make_connection(
host=None,
port=389,
encryption=None,
ciphers=None,
validate=False,
ca_certs=None,
username=None,
password=None,
):
2017-12-16 23:03:03 +01:00
# TLSv1.2 is supported since Python 3.4
if encryption is None:
log.warning("The connection to the LDAP server will not be encrypted.")
2017-12-16 23:03:03 +01:00
tls = None
elif encryption == "TLSv1.2":
log.info("The connection to the LDAP server will use TLSv1.2.")
tls = Tls(version=PROTOCOL_TLSv1_2)
else:
raise NotImplementedError("Sorry, use TLSv1.2.")
if encryption is not None and ciphers is not None:
2020-11-20 12:04:17 +01:00
log.info(
"The connection to the LDAP server will use the "
"following ciphers: {}".format(ciphers)
)
2017-12-16 23:03:03 +01:00
tls.ciphers = ciphers
if encryption is not None and validate is True:
2020-11-20 12:04:17 +01:00
log.info(
"The certificate hostname will be checked to match the " "remote hostname."
)
2017-12-16 23:03:03 +01:00
tls.validate = CERT_REQUIRED
if encryption is not None and validate is True and ca_certs is not None:
2020-11-20 12:04:17 +01:00
log.info("Using the following CA certificates: {}".format(ca_certs))
tls.ca_certs_file = ca_certs
2017-12-16 23:03:03 +01:00
server = Server(host=host, port=port, tls=tls)
2020-11-20 12:04:17 +01:00
connection = Connection(
server, user=username, password=password, client_strategy=ASYNC
)
2017-12-16 23:03:03 +01:00
return connection
def open_connection(connection):
log.info("Opening connection to LDAP server.")
connection.open()
if connection.server.tls is not None and connection.server.ssl is False:
log.info("Issuing StartTLS command.")
connection.start_tls()
log.info("Issuing BIND command.")
connection.bind()
def close_connection(connection):
log.info("Closing connection to LDAP server.")
2017-12-16 23:03:03 +01:00
log.info("Issuing UNBIND command.")
connection.unbind()