Example #1
0
def getServer():
    if not Server:
        return None
    if not SERVER or not SERVER[0]:
        return None
    for s in SERVER:
        server = Server(s, connect_timeout=1, use_ssl=True)
        if server.check_availability():
            try:
                with Connection(server):
                    return server
            except:
                continue
    for s in SERVER:
        server = Server(s, connect_timeout=1)
        if server.check_availability():
            return server
    return None
Example #2
0
    def setUpClass(cls):
        cls.schema = SchemaInfo.from_json(edir_8_8_8_schema)
        info = DsaInfo.from_json(edir_8_8_8_dsa_info, cls.schema)
        cls.server = Server.from_definition('MockSyncServer', info, cls.schema)
        cls.connection = Connection(cls.server, user='******', password='******', client_strategy=MOCK_SYNC)

        # create fixtures
        cls.connection.strategy.add_entry('cn=user1,ou=test', {'userPassword': '******', 'revision': 1})
        cls.connection.strategy.add_entry('cn=user2,ou=test', {'userPassword': '******', 'revision': 2})
        cls.connection.strategy.add_entry('cn=user3,ou=test', {'userPassword': '******', 'revision': 3})
Example #3
0
 def test_json_definition(self):
     if not self.connection.strategy.pooled:
         if not self.connection.server.info:
             self.connection.refresh_server_info()
         json_info = self.connection.server.info.to_json()
         json_schema = self.connection.server.schema.to_json()
         info = DsaInfo.from_json(json_info)
         schema = SchemaInfo.from_json(json_schema)
         server1 = Server.from_definition(test_server, info, schema)
         json_info1 = server1.info.to_json()
         json_schema1 = server1.schema.to_json()
         self.assertEqual(json_info, json_info1)
         self.assertEqual(json_schema, json_schema1)
 def server_connect(self):
     server = Server(self.host, port=self.port, get_info=ALL)
     if not server.check_availability():
         raise Exception('LDAP Server is not reachable')
     return server
Example #5
0
    def connect(self):
        """Setup the connection to the LDAP server and authenticate the user.
        """

        # Parse the server URI
        uri = getattr(config, 'LDAP_SERVER_URI', None)

        if uri:
            uri = urlparse(uri)

        # Create the TLS configuration object if required
        tls = None

        if type(uri) == str:
            return False, "LDAP configuration error: Set the proper LDAP URI."

        if uri.scheme == 'ldaps' or config.LDAP_USE_STARTTLS:

            ca_cert_file = getattr(config, 'LDAP_CA_CERT_FILE', None)
            cert_file = getattr(config, 'LDAP_CERT_FILE', None)
            key_file = getattr(config, 'LDAP_KEY_FILE', None)
            cert_validate = ssl.CERT_NONE

            if ca_cert_file and cert_file and key_file:
                cert_validate = ssl.CERT_REQUIRED

            try:
                tls = Tls(local_private_key_file=key_file,
                          local_certificate_file=cert_file,
                          validate=cert_validate,
                          version=ssl.PROTOCOL_TLSv1_2,
                          ca_certs_file=ca_cert_file)
            except LDAPSSLConfigurationError as e:
                current_app.logger.exception(
                    "LDAP configuration error: {}\n".format(e))
                return False, "LDAP configuration error: {}\n".format(
                    e.args[0])

        try:
            # Create the server object
            server = Server(uri.hostname,
                            port=uri.port,
                            use_ssl=(uri.scheme == 'ldaps'),
                            get_info=ALL,
                            tls=tls,
                            connect_timeout=config.LDAP_CONNECTION_TIMEOUT)
        except ValueError as e:
            return False, "LDAP configuration error: {}.".format(e)

        # Create the connection
        try:
            user_dn = "{0}={1},{2}".format(config.LDAP_USERNAME_ATTRIBUTE,
                                           self.username, config.LDAP_BASE_DN)
            self.conn = Connection(server,
                                   user=user_dn,
                                   password=self.password,
                                   auto_bind=True)

        except LDAPSocketOpenError as e:
            current_app.logger.exception(
                "Error connecting to the LDAP server: {}\n".format(e))
            return False, "Error connecting to the LDAP server:" \
                          " {}\n".format(e.args[0])
        except LDAPBindError as e:
            current_app.logger.exception("Error binding to the LDAP server.")
            return False, "Error binding to the LDAP server."
        except Exception as e:
            current_app.logger.exception(
                "Error connecting to the LDAP server: {}\n".format(e))
            return False, "Error connecting to the LDAP server:" \
                          " {}\n".format(e.args[0])

        # Enable TLS if STARTTLS is configured
        if not uri.scheme == 'ldaps' and config.LDAP_USE_STARTTLS:
            try:
                self.conn.start_tls()
            except LDAPStartTLSError as e:
                current_app.logger.exception(
                    "Error starting TLS: {}\n".format(e))
                return False, "Error starting TLS: {}\n".format(e.args[0])

        return True, None
Example #6
0
def create_LDAP_user(ldap_client_server,ldap_client_server_port,ldap_base_dn,ldap_bind_user,ldap_bind_user_password):
    '''
    use ldap3 create user
    input: connect LDAP objectClass=user
    return: create user time
    author: Jia Liu
    ''' 
    start = time.time()
    server = Server(host=ldap_client_server,port=int(ldap_client_server_port),get_info=ALL,connect_timeout=2)
    conn = Connection(server, ldap_bind_user, ldap_bind_user_password, auto_bind=True,receive_timeout=2)
    conn.search(ldap_base_dn, '(&(objectCategory=person)(objectClass=user))', attributes=['distinguishedName','sAMAccountName','cn','userPrincipalName','userAccountControl','objectSID'])
    result = conn.entries
    AD_List = list(filter(lambda x: not "CN=Users"  in str(x['distinguishedName']).split(','), result))
    DN_User_List = []
    AD_User_List= []
    AD_User_SID = []
    Disable_User_List = []
    Enable_User_List = []
    diffAddUserList = []
    diffDeleteUserList = []
    ADduplicateUserList = []
    ad_flag = True
    #Get user DN, user account, user user Account to lists.
    for ldap in AD_List:
        ldapJson = json.loads(ldap.entry_to_json())
        getUserList = ldapJson
        getUsername = ldapJson['attributes']['sAMAccountName']
        disableUser = ldapJson['attributes']['userAccountControl']
        getUserSID = ldapJson['attributes']['objectSid']
        AD_User_List.extend(getUsername)
        DN_User_List.append(getUserList)
        AD_User_SID.extend(getUserSID)
        if disableUser[0] == 514:
            Disable_User_List.extend(getUsername)
        else:
            Enable_User_List.extend(getUsername)
  
    #Get OmUserList from LDAP created.
    OmUserList = list(OmUser.objects.filter(ad_flag=ad_flag).values_list('ad_sid',flat=True))
    OmUserNonADList = list(OmUser.objects.filter(ad_flag=False).values_list('username',flat=True))
    duplicateUserList = list(set(AD_User_List) & set(OmUserNonADList))
    AD_Exclude_Duplicate_User_List = list(filter(lambda x: not x['attributes']['sAMAccountName'][0] in duplicateUserList, DN_User_List))
    AD_Duplicate_User_List = list(filter(lambda x: x['attributes']['sAMAccountName'][0] in duplicateUserList, DN_User_List))
    
    for ADduplicateUserdict in AD_Duplicate_User_List:
        User_sid =  ADduplicateUserdict['attributes']['objectSid']
        ADduplicateUserList.extend(User_sid)
    if len(OmUserList) == 0:
        OmUser.objects.bulk_create([
            OmUser(
                username = userList['attributes']['sAMAccountName'][0],
                nick_name = userList['attributes']['cn'][0],
                email = userList['attributes']['userPrincipalName'][0],
                ad_sid = userList['attributes']['objectSid'][0],
                ad_flag = ad_flag,
                is_active = False,
                ) for userList in AD_Exclude_Duplicate_User_List])
        diffAddUserList = ["all users are created."]
    elif OmUserList == AD_User_SID:
        pass
    elif OmUserList != AD_User_SID:
        diffAddUserList = list(set(AD_User_SID).difference(set(OmUserList)))
        diffDeleteUserList = list(set(OmUserList).difference(set(AD_User_SID)))
        excludeDuplicateAddUserList = list(set(diffAddUserList).difference(set(ADduplicateUserList)))
        excludeDuplicateDeleteUserList = list(set(diffDeleteUserList).difference(set(ADduplicateUserList)))
        if len(diffAddUserList) > 0 :
            try:
                #From AD_User_List get user account name,if user account name is equal to diffAddUserList,create AddUser from AddUserList.
                OmUser.objects.bulk_create([
                    OmUser(
                        username = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['sAMAccountName'][0],
                        nick_name = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['cn'][0],
                        email = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['userPrincipalName'][0],
                        ad_sid = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['objectSid'][0],
                        ad_flag = ad_flag,
                    ) for add_user in excludeDuplicateAddUserList])
            except Exception as e:
                for add_user in excludeDuplicateAddUserList:
                    username_ad = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['sAMAccountName'][0]
                    try:
                        user_get = OmUser.objects.get(username = username_ad)
                        user_get.username = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['sAMAccountName'][0]
                        user_get.nick_name = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['cn'][0]
                        user_get.email = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['userPrincipalName'][0]
                        user_get.ad_sid = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['objectSid'][0]
                        user_get.is_active = False
                        user_get.delete = False
                        user_get.ad_flag = ad_flag
                        user_get.save()
                    except:
                        add_username = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['sAMAccountName'][0]
                        add_nick_name = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['cn'][0]
                        add_email = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['userPrincipalName'][0]
                        add_ad_sid = list(filter(lambda user: user['attributes']['objectSid'][0] == add_user, DN_User_List))[0]['attributes']['objectSid'][0]
                        add_ad_flag = ad_flag
                        add_ad_is_active = False
                        OmUser.objects.create(username=add_username,nick_name=add_nick_name,email=add_email,ad_sid=add_ad_sid,ad_flag=add_ad_flag,is_active=add_ad_is_active)  
            debug("excludeDuplicateAddUserList: %s" % excludeDuplicateAddUserList)
        if len(diffDeleteUserList) > 0:
            OmUser.objects.filter(ad_sid__in=excludeDuplicateDeleteUserList).update(is_active=False,delete=True)
            debug("excludeDuplicateDeleteUserList: %s" % excludeDuplicateDeleteUserList)
    #execute enable user action.
    license_user_num = getUsers()
    now_users_num = OmUser.objects.filter(delete=False,is_active=True).exclude(username='******').count()
    now_users_list = list(OmUser.objects.filter(delete=False,is_active=True).exclude(username='******').values_list('username',flat=True))
    excludeDuplicateEnableUserList = list(set(Enable_User_List).difference(set(OmUserNonADList)))
    excludeDuplicateEnableUserList.sort()
#     if now_users_num < license_user_num:
    for pop_user in now_users_list:
        try:
            pop_index = excludeDuplicateEnableUserList.index(pop_user)
            excludeDuplicateEnableUserList.pop(pop_index)
        except Exception as e:
            pass
    enableusercount = license_user_num - now_users_num
    OmUser.objects.filter(username__in=excludeDuplicateEnableUserList[0:enableusercount]).update(is_active=True)
    OmUser.objects.filter(username__in=excludeDuplicateEnableUserList[enableusercount:]).update(is_active=False)
    #execute disable user action.
    excludeDuplicateDisableUserList = list(set(Disable_User_List).difference(set(OmUserNonADList)))
    OmUser.objects.filter(username__in=excludeDuplicateDisableUserList).update(is_active=False,delete=False)
   
    debug("excludeDuplicateDisableUserList: %s" % excludeDuplicateDisableUserList)
    debug("excludeDuplicateEnableUserList: %s" % excludeDuplicateEnableUserList)
    conn.unbind()
    end = time.time()
    execute_time = end-start
    return info("User create successful,execute time: %.4f second." % (execute_time))
Example #7
0
 def __init__(self, ldap_server_host, ldap_admin_dn, ldap_admin_password, ldap_server_port=389, ldap_use_ssl=False):
     self._ldap_admin_dn = ldap_admin_dn
     self._ldap_admin_password = ldap_admin_password
     # ldap_server_pool = ServerPool(["172.16.0.102",'172.16.0.103'])
     self.ldap_server = Server(ldap_server_host, port=ldap_server_port, use_ssl=ldap_use_ssl)
Example #8
0
 def server(self) -> Server:
     """Property decorated function: WYSIWYG."""
     if not self._server:
         self._server = Server(self.uri, **self._server_args)
     return self._server
Example #9
0
#!/usr/bin/python3

from hashlib import md5
from binascii import b2a_base64
from ldap3 import Server, Connection

server = Server('ldap://192.168.0.200:389')
ldap = Connection(server, 'cn=admin, dc=dexter, dc=com, dc=br', '4linux')
ldap.bind()

senha = b2a_base64(md5('123'.encode('utf-8')).digest()).decode('utf-8')

user = {
    'cn': 'Rafael',
    'sn': 'Rafael Silva',
    'mail': '*****@*****.**',
    'uid': '1',
    'userPassword': '******' + senha
}
objectClass = ['top', 'person', 'organizationalPerson', 'inetOrgPerson']
dn = 'mail=' + user['mail'] + ',dc=dexter, dc=com, dc=br'
print(ldap.add(dn, objectClass, user))
Example #10
0
#!/usr/bin/env python3

import datetime
import time
from pprint import pprint
from ldap3 import Server, Connection, SEARCH_SCOPE_WHOLE_SUBTREE

USER = "******"
PASS = "******"
BASEDN = "OU=Users,DC=local"
SERVER = Server("127.0.0.1", port=389)
ATTRIBUTES = ['mail', 'pwdLastSet']


def construct_filter(wintimestamp):
    return """(&
       (objectCategory=Person)
       (objectCategory=User)
       (userAccountControl=512)
       (pwdLastSet<={wintimestamp})
       (mail=*)
    )""".format(wintimestamp=wintimestamp)


def search(filter):
    with Connection(SERVER, user=USER, password=PASS) as c:
        c.search(BASEDN,
                 filter,
                 SEARCH_SCOPE_WHOLE_SUBTREE,
                 attributes=ATTRIBUTES)
        return [record['attributes'] for record in c.response]
Example #11
0
    return cxn


def get_ldaps_connection(host,
                         username,
                         password,
                         pfx_path="hr.pfx",
                         pfx_password=PFX_PASSWORD):
    _pfx_to_pem(pfx_path, pfx_password)
    cxn = _get_connection(host, username, password)
    return cxn


# ad = get_ldaps_connection('DC1.busmarket.ua', DC_USERNAME, DC_PASSWORD)

server = Server(DC_SERVER, use_ssl=True, get_info=ALL)
# ad = Connection(server, client_strategy='ASYNC', auto_bind=False, user=DC_USERNAME, password=DC_PASSWORD, pool_size=10)

ad = Connection(server,
                auto_bind=False,
                user=DC_USERNAME,
                password=DC_PASSWORD,
                pool_size=10,
                client_strategy='RESTARTABLE')


def authenticate(login, password):
    try:
        # ad_ = get_ldaps_connection("DC1.busmarket.ua", login, password)
        ad_ = Connection(server,
                         auto_bind=True,
Example #12
0
def get_connection(bind=None,
                   use_ssl=None,
                   check_names=None,
                   lazy_connection=None,
                   authentication=None,
                   sasl_mechanism=None,
                   sasl_credentials=None,
                   ntlm_credentials=(None, None),
                   get_info=None,
                   usage=None,
                   fast_decoder=None,
                   simple_credentials=(None, None)):
    if bind is None:
        bind = True
    if check_names is None:
        check_names = test_check_names
    if lazy_connection is None:
        lazy_connection = test_lazy_connection
    if authentication is None:
        authentication = test_authentication
    if get_info is None:
        get_info = test_get_info
    if usage is None:
        usage = test_usage
    if fast_decoder is None:
        fast_decoder = test_fast_decoder
    if test_server_type == 'AD' and use_ssl is None:
        use_ssl = True  # Active directory forbids Add operations in cleartext
    if isinstance(test_server, (list, tuple)):
        server = ServerPool(pool_strategy=test_pooling_strategy,
                            active=test_pooling_active,
                            exhaust=test_pooling_exhaust)
        for host in test_server:
            server.add(
                Server(host=host,
                       use_ssl=use_ssl,
                       port=test_port_ssl if use_ssl else test_port,
                       allowed_referral_hosts=('*', True),
                       get_info=get_info,
                       mode=test_server_mode))
    else:
        server = Server(host=test_server,
                        use_ssl=use_ssl,
                        port=test_port_ssl if use_ssl else test_port,
                        allowed_referral_hosts=('*', True),
                        get_info=get_info,
                        mode=test_server_mode)

    if authentication == SASL:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          authentication=SASL,
                          sasl_mechanism=sasl_mechanism,
                          sasl_credentials=sasl_credentials,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage,
                          fast_decoder=fast_decoder)
    elif authentication == NTLM:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          user=ntlm_credentials[0],
                          password=ntlm_credentials[1],
                          authentication=NTLM,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage,
                          fast_decoder=fast_decoder)
    else:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          user=simple_credentials[0] or test_user,
                          password=simple_credentials[1] or test_password,
                          authentication=authentication,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage,
                          fast_decoder=fast_decoder)
 def init(self) -> None:
     self.server = Server(self.ldap_uri, port=self.port, use_ssl=self.ssl)
Example #14
0
def ldap_conn(host, use_ssl, bind_dn, password):
    server = Server(host, use_ssl=use_ssl)
    conn = Connection(server, bind_dn, password)
    return conn
Example #15
0
 def initConnection(self):
     self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
     self.session = Connection(self.server, user="******", password="******", authentication=NTLM)
     self.session.open(False)
     return True
def login(username: str, password: str) -> tuple:

    try:
        if SERVER.lower().startswith("ldaps://"):
            server = Server(SERVER, port=PORT, get_info=NONE, use_ssl=True)
        else:
            server = Server(
                SERVER, port=PORT, get_info=NONE, use_ssl=False
            )  # define an unsecure LDAP server, requesting info on DSE and schema

        c = None

        if BIND_DN is not None and BIND_DN != '':
            c = Connection(server,
                           auto_bind=True,
                           client_strategy=SYNC,
                           user=BIND_DN,
                           password=BIND_PASSWORD,
                           authentication=SIMPLE,
                           check_names=True)
        else:
            c = Connection(server,
                           auto_bind=True,
                           client_strategy=SYNC,
                           user=None,
                           password=None,
                           authentication=ANONYMOUS,
                           check_names=True)

    except Exception as e:
        error = "Error connecting to LDAP server: %s" % e
        raise LDAPLoginError({"error_message": error})

    try:
        if (SEARCH_SUFFIX is not None and SEARCH_SUFFIX != ''):
            search_filter = '(%s=%s)' % (SEARCH_PROPERTY,
                                         username + SEARCH_SUFFIX)
        else:
            search_filter = '(%s=%s)' % (SEARCH_PROPERTY, username)
        if SEARCH_FILTER:
            search_filter = '(&%s(%s))' % (search_filter, SEARCH_FILTER)
        c.search(
            search_base=SEARCH_BASE,
            search_filter=search_filter,
            search_scope=SUBTREE,
            attributes=[EMAIL_PROPERTY, GIVEN_NAME_PROPERTY, SURNAME_PROPERTY],
            paged_size=5)

        if len(c.response) > 0:
            dn = c.response[0].get('dn')
            user_email = c.response[0].get('raw_attributes').get(
                EMAIL_PROPERTY)[0].decode('utf-8')
            first_name = c.response[0].get('raw_attributes').get(
                GIVEN_NAME_PROPERTY)[0].decode('utf-8')
            last_name = c.response[0].get('raw_attributes').get(
                SURNAME_PROPERTY)[0].decode('utf-8')

            full_name = first_name + " " + last_name

            user_conn = Connection(server,
                                   auto_bind=True,
                                   client_strategy=SYNC,
                                   user=dn,
                                   password=password,
                                   authentication=SIMPLE,
                                   check_names=True)

            return (user_email, full_name)

        raise LDAPLoginError(
            {"error_message": "Username or password incorrect"})

    except Exception as e:
        error = "LDAP account or password incorrect: %s" % e
        raise LDAPLoginError({"error_message": error})
Example #17
0
 def __init__(self, ldap_servers):
     self.serverPool = ServerPool(None, ROUND_ROBIN)
     for ldapServer in ldap_servers:
         self.serverPool.add(Server(ldapServer))
Example #18
0
from ldap3 import Server, Connection, MODIFY_ADD, MODIFY_REPLACE, ALL_ATTRIBUTES, SUBTREE, LEVEL, BASE
from ldap3.core.exceptions import LDAPBindError
from ldap3.utils.dn import safe_rdn
from flask import Flask, jsonify, abort, request, make_response, url_for
import random

server = Server('zeus')
app = Flask(__name__, static_url_path="")

# print(0, conn.extend.standard.who_am_i())
users = {}


@app.route('/login', methods=['POST'])
def login():
    if not request.json:
        return "Not JSON", 400
    if not "username" in request.json:
        return "No Username", 400
    if not "password" in request.json:
        return "No password", 400
    try:
        conn = Connection(server,
                          'uid=' + request.json["username"] +
                          ', ou=People, dc=nodomain ',
                          request.json["password"],
                          auto_bind=True)
        ### TODO Create a random hash with uid and post it somewhere (LDAP or a DB)
        hash = random.getrandbits(64)
        users[hash] = request.json['username']
        return jsonify({"logged": 1, "key": hash, "valid": 3600}), 201
Example #19
0
 def init_app(self, app):
     """init ldap client instance, with configs from app."""
     self._server = Server(app.config['LDAP_HOST'], use_ssl=True)
     self._base_search = app.config['LDAP_BASE_SEARCH']
     self._usr = app.config['LDAP_BIND_DN']
     self._pwd = app.config['LDAP_BIND_PASSWD']
def run_search(options, query_definition, event_message):
    """ Run LDAP search and return result """
    # Read the LDAP configuration options
    ldap_server = options["server"]
    ldap_port = int(options["port"] or LDAP_DEFAULT_PORT)
    ldap_user = options["user"]
    ldap_password = options["password"]
    ldap_ssl = options["ssl"] == "True"  # anything else is false
    ldap_auth = LDAP_AUTH_TYPES[options["auth"] or "ANONYMOUS"]
    results = None
    # CLIENT Active Directory
    client_ad_server = Server(ldap_server,
                              ldap_port,
                              get_info=ldap3.ALL,
                              use_ssl=options["ssl"] == "True",
                              connect_timeout=3)

    client_ad_creds = (ldap_user, ldap_password, ldap_auth)

    if query_definition.params is None:
        raise Exception("LDAP query requires 'search_base' parameter")
    search_base = query_definition.params.get("search_base")
    if search_base is None:
        raise Exception("LDAP query requires 'search_base' parameter")

    # Connect to the LDAP server
    LOG.debug("LDAP connect")
    with Connection(client_ad_server,
                    user=client_ad_creds[0],
                    password=client_ad_creds[1],
                    authentication=client_ad_creds[2],
                    auto_bind=True) as conn:

        LOG.debug("LDAP search {0} / {1}".format(search_base,
                                                 query_definition.query))
        conn.search(search_base,
                    query_definition.query,
                    attributes=ldap3.ALL_ATTRIBUTES)

        entries = conn.entries
        if entries is None:
            LOG.info("LDAP query returned None")
            results = {"entries": None}
            if query_definition.default:
                mapdata = copy.deepcopy(event_message)
                mapdata.update(query_definition.vars)
                mapdata.update({"query": query_definition.query})
                default_template = json.dumps(
                    {"entries": [query_definition.default]}, indent=2)
                default_rendered = template_functions.render_json(
                    default_template, mapdata)
                results = default_rendered
        else:
            # List of entries.
            entries = json.loads(conn.response_to_json())["entries"]
            LOG.info("Result contains %s entries", len(entries))
            # Each entry has 'dn' and dict of 'attributes'.  Move attributes to the top level for easier processing.
            for entry in entries:
                entry.update(entry.pop("attributes", None))
            results = {"entries": entries}

    LOG.debug(json.dumps(results, indent=2))
    return results
 def setUp(self):
     schema = SchemaInfo.from_json(edir_8_8_8_schema)
     info = DsaInfo.from_json(edir_8_8_8_dsa_info, schema)
     server = Server.from_definition('MockSyncServer', info, schema)
     self.connection = Connection(server, user='******', password='******', client_strategy=MOCK_SYNC)
Example #22
0
    def entroPass(self, user, password):
        # First check if it is a clear text
        dc_test_conn = Server(self.server, get_info=ALL)
        test_conn = Connection(dc_test_conn, user=user, password=password)
        test_conn.bind()
        # Validate the login (bind) request
        if int(test_conn.result['result']) != 0:
            if self.CREDS:
                print(
                    '[ ' + colored('INFO', 'yellow') +
                    ' ] User: "******" with: "{1}" as possible clear text password'
                    .format(user, password))
            else:
                print('[ ' + colored('INFO', 'green') +
                      ' ] User: "******" with: "{1}" was not cleartext'.format(
                          user, password))
        else:
            if self.CREDS:
                print(
                    '[ ' + colored('INFO', 'yellow') +
                    ' ] User: "******" had cleartext password of: "{1}" in a property'
                    .format(user, password))
            else:
                print(
                    '[ ' + colored('OK', 'yellow') +
                    ' ] User: "******" had cleartext password of: "{1}" in a property - continuing with these creds'
                    .format(user, password))
                print('')
                return user, password

        test_conn.unbind()

        # Attempt for base64
        # Could be base64, lets try
        pw = base64.b64decode(bytes(password,
                                    encoding='utf-8')).decode('utf-8')

        # Attempt decoded PW
        dc_test_conn = Server(self.server, get_info=ALL)
        test_conn = Connection(dc_test_conn, user=user, password=pw)
        test_conn.bind()
        # Validate the login (bind) request
        if int(test_conn.result['result']) != 0:
            if self.CREDS:
                print(
                    '[ ' + colored('INFO', 'yellow') +
                    ' ] User: "******" with: "{1}" as possible base64 decoded password'
                    .format(user, pw))
            else:
                print('[ ' + colored('INFO', 'green') +
                      ' ] User: "******" with: "{1}" was not base64 encoded'.
                      format(user, pw))
        else:
            if self.CREDS:
                print(
                    '[ ' + colored('INFO', 'yellow') +
                    ' ] User: "******" had base64 encoded password of: "{1}" in a property'
                    .format(user, pw))
            else:
                print(
                    '[ ' + colored('OK', 'yellow') +
                    ' ] User: "******" had base64 encoded password of: "{1}" in a property - continuing with these creds'
                    .format(user, pw))
                print('')
                return user, pw
Example #23
0
def verifyuser_login(sAMAccountName, password):
    try:
        with ldap3RESTARTABLE as conn:
            conn.search(
                search_base=ladp3search_base,
                search_filter="(&(objectCategory=person)(objectClass=user)(sAMAccountName=" +sAMAccountName +"))",
                search_scope='SUBTREE',
                attributes=['distinguishedName'],
            )
            result_id = conn.result
            response_id = conn.response
            if result_id['result'] == 0:
                message = response_id[0].get('attributes', '')
                if message:
                    conn.search(
                        search_base=ladp3search_base,
                        search_filter="(&(sAMAccountName=" +sAMAccountName +")(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2))))",
                        search_scope='SUBTREE',
                        attributes=['distinguishedName'],
                    )
                    result_id = conn.result
                    response_id = conn.response
                    if result_id['result'] == 0:
                        message = response_id[0].get('attributes', '')
                        if message:
                            conn.search(
                                search_base=ladp3search_base,
                                search_filter="(&(sAMAccountName=" + sAMAccountName + ")(&(objectCategory=person)(objectClass=user)(lockoutTime>=1)))",
                                search_scope='SUBTREE',
                                attributes=['distinguishedName'],
                            )
                            result_id = conn.result
                            response_id = conn.response
                            if result_id['result'] == 0:
                                message = response_id[0].get('attributes', '')
                                if message:
                                    result = {'isSuccess': False, "message": '账号锁定'}
                                else:
                                    try:
                                        server = Server(ladp3search_server, get_info=ALL)
                                        user = ladp3search_domain+'\\' + sAMAccountName
                                        with Connection(server, user, password, auto_bind=True) as conn:
                                            conn.search(
                                                search_base=ladp3search_base,
                                                search_filter="(&(objectCategory=person)(objectClass=user)(sAMAccountName=" +
                                                              sAMAccountName +
                                                              "))",
                                                attributes=[
                                                    'cn',
                                                    'name',
                                                    'sn',
                                                    'givenName',
                                                    'sAMAccountName',
                                                    'userPrincipalName',
                                                    'displayName',
                                                    'wWWHomePage',
                                                    'description',
                                                    'physicalDeliveryOfficeName',
                                                    'mail',
                                                    'distinguishedName',
                                                    # 'memberof',
                                                    'userAccountControl'])
                                            attributes_user = conn.response[0].get('attributes', '')
                                            if attributes_user:
                                                result = {'isSuccess': True, "message": attributes_user}
                                            else:
                                                result = {'isSuccess': False, "message": '没有查询到用户属性'}
                                    except Exception as e:
                                        result = {'isSuccess': False, "message": '密码错误'}
                            else:
                                result = {'isSuccess': False, "message": '账号锁定'}
                        else:
                            result = {'isSuccess': False, "message": '账号已禁用'}
                    else:
                        result = {'isSuccess': False, "message": '未查询到账号'}
                else:
                    result = {'isSuccess': False, "message": '账户不存在'}
            else:
                result = {'isSuccess': False, "message": '账户不存在'}
    except Exception as e:
        result = {'isSuccess': False, "message": '出现异常'}
    return result
Example #24
0
# from utils.config import config
# from utils.models import LdapUser

login_manager = LoginManager()

# Pour ton info, dans la config du prog
ldap_provider = '127.0.0.1'
ldap_use_ssl = True
# au moins quand tu es sur place
# Sinon tu peux utiliser un pont ssh
# sudo ssh -L 389:157.159.10.70:389 [email protected] -i ./.ssh/id_rsa
# NB: il faut le sudo parceque je me bind a un port < 1024 sur mon ordi. Si tu veux un port au dessus, pas besoin de sudo.
# remplaces jovart_a par ton login, et le chemin vers ta clé ssh si besoin

server = Server(ldap_provider, use_ssl=ldap_use_ssl)


def func_authenticate(username, password, use_password=True):
    """
    Vérifie qu'un nom d'utilisateur et un mot de passe sont valides en authentifiant l'utilisateur avec le serveur LDAP de l'école.
    """
    if "@" in username:
        # L'username est peut etre un mail...
        maybe_username = get_login_from_email(username)
        if maybe_username:
            username = maybe_username

    if use_password:
        conn = Connection(
            server,
Example #25
0
def verifyuser_login_new(sAMAccountName, password):
    try:
        permessa = getpermsessage()
        logongroup = permessa.get('logongroup','')
        with ldap3RESTARTABLE as conn:
            if logongroup:
                conn.search(
                    search_base=ladp3search_base,
                    search_filter="(&(objectCategory=group)(sAMAccountName=" + logongroup + "))",
                    search_scope='SUBTREE',
                )
                result_logongroup = conn.result
                response_logongroup = conn.response
                logongroup_dn = response_logongroup[0].get('dn','')
                if logongroup_dn:
                    conn.search(search_base=ladp3search_base,
                                            search_filter="(&(objectCategory=person)(objectClass=user)(memberof:1.2.840.113556.1.4.1941:=%s)(sAMAccountName=%s))" % (logongroup_dn, sAMAccountName),
                                            attributes=['sAMAccountName', 'userAccountControl', 'lockoutTime', 'distinguishedName','cn','name',
                                                        'sn','givenName','userPrincipalName','displayName','wWWHomePage','description','physicalDeliveryOfficeName','mail', 'accountExpires'])
                    result_user = conn.result
                    response_user = conn.response
                    user_attributes = response_user[0].get('attributes','')
                    if user_attributes:
                        userAccountControl = user_attributes.get('userAccountControl')
                        distinguishedName = user_attributes.get('distinguishedName')
                        lockoutTime = user_attributes.get('lockoutTime', '')
                        accountExpires = user_attributes.get('accountExpires', datetime.now())
                        if lockoutTime:
                            lockoutTime_str = (utc2local(lockoutTime)).strftime('%Y-%m-%d %H:%M:%S')
                        else:
                            lockoutTime_str = '1601-01-01 08:00:00'
                        # accountExpires  9999-12-31 23:59:59.999999 未设置账户过期
                        # accountExpires 1601-01-01 00:00:00+00:00 从不过期
                        # accountExpires 2019-05-17 16:00:00+00:00 账户过期时间
                        accountExpires_str = accountExpires.strftime('%Y-%m-%d %H:%M:%S')
                        if accountExpires_str in ['1601-01-01 00:00:00', '9999-12-31 23:59:59']:
                            Expires = True
                        else:
                            accountExpires = (utc2local(accountExpires)).replace(tzinfo=None)
                            now = (datetime.now()).replace(tzinfo=None)
                            if accountExpires > now:
                                Expires = True
                            else:
                                accountExpires_str = accountExpires.strftime('%Y-%m-%d %H:%M:%S')
                                Expires = False
                        if bin(userAccountControl)[-2] == '0':
                            if lockoutTime_str == '1601-01-01 08:00:00':
                                if Expires:
                                    try:
                                        server = Server(ladp3search_server, get_info=NONE)
                                        connect = Connection(server=server, user=distinguishedName, password=password)
                                        bind = connect.bind(read_server_info=False)
                                        if bind:
                                            result = {'isSuccess': True, "message": user_attributes}
                                        else:
                                            result = {'isSuccess': False, "message": '密码错误'}
                                    except Exception as e:
                                        result = {'isSuccess': False, "message": '服务器连接ldap错误'+str(e)}
                                else:
                                    result = {'isSuccess': False, "message": sAMAccountName + '账号已过期,过期时间' + accountExpires_str}
                            else:
                                result = {'isSuccess': False, "message": sAMAccountName + '账号已锁定,锁定时间'+lockoutTime_str}
                        else:
                            result = {'isSuccess': False, "message": sAMAccountName+'账号已禁用'}
                    else:
                        result = {'isSuccess': False, "message": sAMAccountName+'账号错误或没有权限'}
                else:
                    result = {'isSuccess': False, "message": '登陆权限组配置错误:'+str(result_logongroup.get('description',''))}
            else:
                result = {'isSuccess': False, "message": '登陆权限组未配置'}
    except Exception as e:
        result = {'isSuccess': False, "message": '服务器错误:'+str(e)}
    return result
Example #26
0
def create_LDAP_group(ldap_client_server,ldap_client_server_port,ldap_base_dn,ldap_bind_user,ldap_bind_user_password):
    '''
    use ldap3 create group
    input: connect LDAP organization unit
    return: create group time
    author: Jia Liu
    ''' 
    start = time.time()
    # search LDAP organization unit return all result
    server = Server(host=ldap_client_server,port=int(ldap_client_server_port), get_info=ALL,connect_timeout=2)
    conn = Connection(server, ldap_bind_user, ldap_bind_user_password, auto_bind=True,receive_timeout=2)
    conn.search(ldap_base_dn, '(objectCategory=organizationalUnit)', attributes=['OU','distinguishedName'])
    result = conn.entries
    #Set default need parameter
    AD_OU_List = []
    diffAddTupleList = []
    diffdeleteTupleList = []
    functional_flag = False
    ad_flag = True
    OmGroupstr_List = list(OmGroup.objects.filter(ad_flag=ad_flag).values_list('name',flat=True))
    OmGroup_List = []
    #string type list to list type.
    for GroupList in OmGroupstr_List:
        OmGroup_List.append(ast.literal_eval(GroupList))
    #Get list[0] value,and value combine to OU list,append to AD_OU_List.
    for ldap in result:
        ldapJson = json.loads(ldap.entry_to_json())
        getOU = ldapJson['attributes']['distinguishedName'][0].split(',')
        AD_OU_List.append(getOU)
        #OmGroupList length is 0,create all group from LDAP AD_OU_List.
    if len(OmGroup_List) == 0:
        for oulist in AD_OU_List:
            group_name = str(oulist[0]).replace("OU=",'')
            #check OU count in list.
            oucount = sum('OU=' in count for count in oulist)
            #count = 1 is head group.
            if oucount == 1:
                OmGroup.objects.create(name=oulist,parent_group=None,functional_flag=functional_flag,display_name=group_name,ad_flag=ad_flag)
            #count > 1 is child group.
            elif oucount > 1:
                if oulist != AD_OU_List[0]:
                    parent_groupname = []
                    parent_groupname.extend(oulist)
                    parent_groupname.pop(0)
                    parent_group_name= parent_groupname
                    parent_group = OmGroup.objects.get(name=parent_group_name)
                    OmGroup.objects.create(name=oulist,parent_group=parent_group,functional_flag=functional_flag,display_name=group_name,ad_flag=ad_flag)
                else:
                    OmGroup.objects.create(name=oulist,parent_group=None,functional_flag=functional_flag,display_name=group_name,ad_flag=ad_flag)
                       
        diffAddTupleList = ["all organization units are created."]
    elif OmGroup_List == AD_OU_List:
        pass
    #Compare two lists,if true, execute add or delete group.
    elif OmGroup_List != AD_OU_List:
        set_AD_OU_List = set(map(tuple, AD_OU_List))
        set_OmGroup_List = set(map(tuple, OmGroup_List))
        intersectionTupleList = list(set(set_OmGroup_List).intersection(set(set_AD_OU_List)))
        diffAddTupleList = list(set_AD_OU_List.difference(set_OmGroup_List))
        diffdeleteTupleList = list(set_OmGroup_List.difference(set_AD_OU_List))
        diffAddTupleList.sort(key=len)
        diffdeleteTupleList.sort(key=len,reverse=True)
        intersectionTupleList.sort(key=len)
        if diffdeleteTupleList != []:
            for deletegroupTuple in diffdeleteTupleList:
                deletegroupList = list(deletegroupTuple)
                group = OmGroup.objects.get(name=deletegroupList)
                group.delete()
        if diffAddTupleList != []:
            for addgroupTuple in diffAddTupleList:
                addgroupList = list(addgroupTuple)
                group_name = str(addgroupList[0]).replace("OU=",'')
                oucount = sum('OU=' in count for count in addgroupList)
                if OmGroup.objects.filter(name=addgroupList).exists():
                    pass
                elif oucount == 1:
                    OmGroup.objects.create(name=addgroupList,parent_group=None,functional_flag=functional_flag,display_name=group_name,ad_flag=ad_flag)
                elif oucount > 1:
                    if addgroupTuple != diffAddTupleList[0]:
                        parent_groupname = []
                        parent_groupname.extend(addgroupList)
                        parent_groupname.pop(0)
                        parent_group_name= parent_groupname
                        parent_group = OmGroup.objects.get(name=parent_group_name)
                        OmGroup.objects.create(name=addgroupList,parent_group=parent_group,functional_flag=functional_flag,display_name=group_name,ad_flag=ad_flag)
                    else:
                        OmGroup.objects.create(name=addgroupList,parent_group=None,functional_flag=functional_flag,display_name=group_name,ad_flag=ad_flag)
        if intersectionTupleList != []:
            for intersectionGroupTuple in intersectionTupleList:
                intersectionGroupList = list(intersectionGroupTuple)
                oucount = sum('OU=' in count for count in intersectionGroupList)
                if oucount == 1:
                    pass
                elif oucount > 1:
                    if OmGroup.objects.filter(name=intersectionGroupList).exists():
                        group_name = OmGroup.objects.get(name=intersectionGroupList)
                        parent_groupname = []
                        parent_groupname.extend(intersectionGroupList)
                        parent_groupname.pop(0)
                        parent_group_name= parent_groupname
                        if OmGroup.objects.filter(name=parent_group_name).exists():
                            parent_group = OmGroup.objects.get(name=parent_group_name)
                            group_name.parent_group = parent_group
                            group_name.save()
                    else:
                        group_name = str(intersectionGroupList[0]).replace("OU=",'')
                        if intersectionGroupTuple != intersectionTupleList[0]:
                            parent_groupname = []
                            parent_groupname.extend(intersectionGroupList)
                            parent_groupname.pop(0)
                            parent_group_name= parent_groupname
                            parent_group = OmGroup.objects.get(name=parent_group_name)
                            OmGroup.objects.create(name=intersectionGroupList,parent_group=parent_group,functional_flag=functional_flag,display_name=group_name,ad_flag=ad_flag)
                        else:
                            OmGroup.objects.create(name=intersectionGroupList,parent_group=None,functional_flag=functional_flag,display_name=group_name,ad_flag=ad_flag)
    debug("diffAddTupleList: %s" % diffAddTupleList)
    debug("diffdeleteTupleList: %s" % diffdeleteTupleList)
    conn.unbind()
    end = time.time()
    execute_time = end-start
    return info("Group create successful,execute time: %.4f second." % (execute_time))
Example #27
0
from ldap3 import Server, Connection, SUBTREE, ALL, Tls
import ssl

total_entries = 0
tls = Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1)
server = Server(
    'RPW-DC03.crii.org', get_info=ALL, use_ssl=True, tls=tls
)  # define an unsecure LDAP server, requesting info on DSE and schema
c = Connection(server)
c.search(search_base='CN=Users',
         search_filter='(objectClass=inetOrgPerson)',
         search_scope=SUBTREE,
         attributes=['cn', 'givenName'],
         paged_size=5)
# total_entries += len(c.response)
# for entry in c.response:
#     print(entry['dn'], entry['attributes'])
# cookie = c.result['controls']['1.2.840.113556.1.4.319']['value']['cookie']
# while cookie:
#     c.search(search_base = 'o=test',
#              search_filter = '(objectClass=inetOrgPerson)',
#              search_scope = SUBTREE,
#              attributes = ['cn', 'givenName'],
#              paged_size = 5,
#              paged_cookie = cookie)
#     total_entries += len(c.response)
#     cookie = c.result['controls']['1.2.840.113556.1.4.319']['value']['cookie']
#     for entry in c.response:
#         print(entry['dn'], entry['attributes'])
# print('Total entries retrieved:', total_entries)
Example #28
0
def mapping_group_user(ldap_client_server,ldap_client_server_port,ldap_base_dn,ldap_bind_user,ldap_bind_user_password):
    '''
    use ldap3 mapping group and user
    input: connect LDAP objectClass=user
    return: mapping time
    author: Jia Liu
    ''' 
    start = time.time()
    server = Server(host=ldap_client_server,port=int(ldap_client_server_port), get_info=ALL,connect_timeout=2)
    conn = Connection(server, ldap_bind_user, ldap_bind_user_password, auto_bind=True,receive_timeout=2)
    conn.search(ldap_base_dn, '(&(objectCategory=person)(objectClass=user))', attributes=['distinguishedName','sAMAccountName','cn','userPrincipalName','userAccountControl'])
    result = conn.entries
    dict_OU_Group = {}
    dict_Omuser_Group = {}
    #Get AD List ,exclude group CN=Users and None.
    AD_List = list(filter(lambda x: not "CN=Users"  in str(x['distinguishedName']).split(','), result))
    #Get OmGroupList from LDAP created.
    OmGroupstr_List = list(OmGroup.objects.filter(ad_flag=True).values_list('name',flat=True))
    #Exclude same username in ad_flag = False in user list.
    OmUserNonADList = list(OmUser.objects.filter(ad_flag=False).values_list('username',flat=True))
    AD_Exclude_Duplicate_User_List = list(filter(lambda x: not x['sAMAccountName'][0] in OmUserNonADList, AD_List))
    #Count LDAP groups_id from Omuser_group.
    Omuser_Groups_count  = OmUser.objects.filter(ad_flag=True).values('id').aggregate(count = Count('groups'))
    OmGroup_List = []
    #string type list to list type.
    for GroupList in OmGroupstr_List:
        OmGroup_List.append(ast.literal_eval(GroupList))

    for groupnameList in OmGroup_List:
        #dictionaries value set list type.
        dict_OU_Group[str(groupnameList)] = []
        dict_Omuser_Group[str(groupnameList)] = []
        #Get LDAP group id and append to dictionaries from Omuser_Groups.
        OmuserGroups_id_List = list(OmUser.objects.filter(ad_flag=True,groups__name=groupnameList).values_list('id',flat = True))
        dict_Omuser_Group[str(groupnameList)].extend(OmuserGroups_id_List)
        dict_Omuser_Group[str(groupnameList)].sort()
        #Get group name from sublist in AD_List.
        AD_Group_User_List = list(filter(lambda x: ','.join(groupnameList)  in x['distinguishedName'][0], AD_Exclude_Duplicate_User_List))
        #Get LDAP group id and append to dictionaries from AD_Group_User_List.
        for AD_user in AD_Group_User_List:
            user = AD_user['sAMAccountName'][0]
            omuserid = OmUser.objects.get(username=user).id
            dict_OU_Group[str(groupnameList)].append(omuserid)
        dict_OU_Group[str(groupnameList)].sort()

    #Compare two dictionaries,get add_group_dict and delete_group_dict.
    addGroupDict    = dict( (key, list(set(dict_OU_Group[key])- set(dict_Omuser_Group[key])))
                        for key in (set(dict_OU_Group) & set(dict_Omuser_Group))
                            if dict_OU_Group[key] != dict_Omuser_Group[key])
  
    deleteGroupDict = dict( (key, list(set(dict_Omuser_Group[key]) -set(dict_OU_Group[key])))
                        for key in (set(dict_Omuser_Group) & set(dict_OU_Group))
                            if dict_Omuser_Group[key] != dict_OU_Group[key])
    if Omuser_Groups_count['count'] == 0:   
        for groupname_OU_List in OmGroup_List:
            omgroup = OmGroup.objects.get(name=groupname_OU_List)
            omgroup.user_set.add(*dict_OU_Group[str(groupname_OU_List)])
    if addGroupDict != {}:
        for key,value in addGroupDict.items():
            omgroup = OmGroup.objects.get(name=str(key))
            omgroup.user_set.add(*value)
    if deleteGroupDict != {}:
        for key,value in deleteGroupDict.items():
            omgroup = OmGroup.objects.get(name=str(key))
            omgroup.user_set.remove(*value)
    debug("dict_OU_Group: %s" % dict_OU_Group)
    debug("addGroupDict: %s" % addGroupDict)
    debug("deleteGroupDict: %s" % deleteGroupDict)
    conn.unbind()
    end = time.time()
    execute_time = end-start
    return info("mapping_group_user is successful,execute time: %.4f second." % (execute_time))
Example #29
0
def create_ldap_user(account_id):
    request = ShellAccount.objects.get(id=account_id)
    user = request.user

    # Setup the LDAP connection
    ldap_server = Server(settings.LDAP_URL, port=settings.LDAP_PORT)
    ldap_conn = Connection(ldap_server,
                           user=settings.LDAP_USER,
                           password=settings.LDAP_PASSWORD,
                           client_strategy=SYNC,
                           authentication=SIMPLE)
    ldap_conn.bind()

    # Search for the user on LDAP
    search_string_user = '******'.format(
        username=request.name)
    search_string_group = 'cn={username},ou=Group,dc=uwcs,dc=co,dc=uk'.format(
        username=request.name)

    ldap_conn.search(search_string_user,
                     '(objectClass=*)',
                     attributes=ALL_ATTRIBUTES)
    user_search = ldap_conn.response

    ldap_conn.search(search_string_group,
                     '(objectClass=*)',
                     attributes=ALL_ATTRIBUTES)
    group_search = ldap_conn.response

    if user_search or group_search:
        # Update request to 'disabled' as representation of the failure
        request.status = 'DD'
        request.save()

        send_user_issue_email(user, request.name)

        return False
    else:
        password = User.objects.make_random_password(length=20)
        salt = crypt.mksalt(crypt.METHOD_SHA512)
        password_hashed = '{crypt}' + crypt.crypt(password, salt)
        days_since_epoch = (datetime.utcnow() - datetime(1970, 1, 1)).days

        group_add_dn = 'cn={nickname},ou=Groups,dc=uwcs,dc=co,dc=uk'.format(
            nickname=request.name)
        group_attributes_dict = {
            'objectClass': ['posixGroup', 'top'],
            'cn': request.name,
            'gidNumber': [int(user.username)],
            'userPassword': [password_hashed],
        }

        ldap_conn.add(group_add_dn, attributes=group_attributes_dict)

        user_add_dn = 'uid={nickname},ou=People,dc=uwcs,dc=co,dc=uk'.format(
            nickname=request.name)
        user_attributes_dict = {
            'objectClass': ['account', 'posixAccount', 'top', 'shadowAccount'],
            'cn': [user.get_full_name()],
            'gidNumber': [int(user.username)],
            'uid': [request.name],
            'uidNumber': [int(user.username)],
            'homeDirectory':
            ['/compsoc/home/{nickname}'.format(nickname=request.name)],
            'loginShell': ['/bin/bash'],
            'shadowWarning': ['7'],
            'shadowLastChange': [days_since_epoch],
            'shadowMax': ['99999'],
            'gecos': ['{fullname}'.format(fullname=user.get_full_name())],
            'userPassword': [password_hashed],
        }

        ldap_conn.add(user_add_dn, attributes=user_attributes_dict)

        request.status = 'PR'
        request.save()

        sites_path = '/compsoc/sites/{nickname}'.format(nickname=request.name)
        if not os.path.exists(sites_path):
            os.makedirs(sites_path)
            os.chown(sites_path, int(user.username), int(user.username))

        apache_conf_path = '{apache}/member-{nickname}.conf'.format(
            apache=settings.APACHE_SITES_AVAILABLE, nickname=request.name)
        if not os.path.exists(apache_conf_path):
            make_user_site_config(request.name)
            make_user_site_placeholder(username=request.name,
                                       uid=int(user.username))

        send_success_mail(user, request.name, password)

        return True
Example #30
0
File: base.py Project: ammoam/eNMS
 def init_ldap_client(self) -> None:
     self.ldap_client = Server(self.ldap_server, get_info=ALL)
Example #31
0
from django.http import Http404
from decouple import config

from ldap3 import (
    ALL_ATTRIBUTES,
    MODIFY_ADD,
    MODIFY_DELETE,
    MODIFY_REPLACE,
    SYNC,
    Connection,
    Server,
)


LDAP_SERVER_URL = "ldaps://ldap.csua.berkeley.edu"
LDAP_SERVER = Server(LDAP_SERVER_URL, connect_timeout=1)
LDAP_CLIENT_STRATEGY = SYNC
CSUA_DC = "dc=csua,dc=berkeley,dc=edu"
PEOPLE_OU = "ou=People," + CSUA_DC
GROUP_OU = "ou=Group," + CSUA_DC
NEWUSER_DN = "uid=newuser," + PEOPLE_OU
NEWUSER_PW = config("NEWUSER_PW")


@contextmanager
def ldap_connection(**kwargs):
    if "client_strategy" not in kwargs:
        kwargs["client_strategy"] = LDAP_CLIENT_STRATEGY
    else:
        raise RuntimeError(
            "Don't change the client strategy unless you know what you're doing!"
Example #32
0
    def __init__(self, app=None, handler=None):
        """:func:`burpui.misc.auth.ldap.LdapLoader.__init__` establishes a
        connection to the LDAP server.

        :param app: Instance of the app we are running in
        :type app: :class:`burpui.engines.server.BUIServer`
        """
        self.app = app
        conf = self.app.conf
        handler.name = self.name
        defaults = {
            "LDAP:AUTH": {
                "host": "localhost",
                "port": None,
                "encryption": None,
                "binddn": None,
                "bindpw": None,
                "filter": None,
                "base": None,
                "searchattr": "uid",
                "validate": "none",
                "cafile": None,
            }
        }
        mapping = {
            "host": "host",
            "port": "port",
            "encryption": "encryption",
            "filt": "filter",
            "base": "base",
            "attr": "searchattr",
            "binddn": "binddn",
            "bindpw": "bindpw",
            "validate": "validate",
            "cafile": "cafile",
        }
        conf.update_defaults(defaults)
        # Maybe the handler argument is None, maybe the 'priority'
        # option is missing. We don't care.
        try:
            handler.priority = (conf.safe_get(
                "priority", "integer", section=self.section)
                                or handler.priority)
        except:
            pass
        for (opt, key) in mapping.items():
            setattr(self, opt,
                    conf.safe_get(key, "force_string", section=self.section))

        if self.validate and self.validate.lower() in [
                "none", "optional", "required"
        ]:
            self.validate = getattr(ssl,
                                    "CERT_{}".format(self.validate.upper()))
        else:
            self.validate = None
        self.version = ssl.OP_NO_SSLv3
        self.users = []
        self.tls = None
        self.ssl = False
        self.auto_bind = AUTO_BIND_NONE
        if self.encryption == "ssl":
            self.ssl = True
        elif self.encryption == "tls":
            self.tls = Tls(
                local_certificate_file=self.cafile,
                validate=self.validate,
                version=self.version,
            )
            self.auto_bind = AUTO_BIND_TLS_BEFORE_BIND
        if self.port:
            try:
                self.port = int(self.port)
            except ValueError:
                self.logger.error("LDAP port must be a valid integer")
                self.port = None
        self.logger.info("LDAP host: {0}".format(self.host))
        self.logger.info("LDAP port: {0}".format(self.port))
        self.logger.info("LDAP encryption: {0}".format(self.encryption))
        self.logger.info("LDAP filter: {0}".format(self.filt))
        self.logger.info("LDAP base: {0}".format(self.base))
        self.logger.info("LDAP search attr: {0}".format(self.attr))
        self.logger.info("LDAP binddn: {0}".format(self.binddn))
        self.logger.info(
            "LDAP bindpw: {0}".format("*****" if self.bindpw else "None"))
        self.logger.info("TLS object: {0}".format(self.tls))

        try:
            self.server = Server(
                host=self.host,
                port=self.port,
                use_ssl=self.ssl,
                get_info=ALL,
                tls=self.tls,
            )
            self.logger.debug("LDAP Server = {0}".format(str(self.server)))
            if self.binddn:
                self.ldap = Connection(
                    self.server,
                    user=self.binddn,
                    password=self.bindpw,
                    raise_exceptions=True,
                    client_strategy=RESTARTABLE,
                    auto_bind=self.auto_bind,
                    authentication=SIMPLE,
                )
            else:
                self.ldap = Connection(
                    self.server,
                    raise_exceptions=True,
                    client_strategy=RESTARTABLE,
                    auto_bind=self.auto_bind,
                )
            okay = False
            with self.ldap:
                self.logger.debug("LDAP Connection = {0}".format(str(
                    self.ldap)))
                self.logger.info("OK, connected to LDAP")
                okay = True

            if not okay:
                raise Exception("Not connected")

            self._prefetch()
        except Exception as e:
            self.logger.error("Could not connect to LDAP: {0}".format(str(e)))
            self.server = None
            self.ldap = None
Example #33
0
def get_connection(bind=None,
                   use_ssl=None,
                   check_names=None,
                   lazy_connection=None,
                   authentication=None,
                   sasl_mechanism=None,
                   sasl_credentials=None,
                   ntlm_credentials=(None, None),
                   get_info=None,
                   usage=None,
                   fast_decoder=None,
                   simple_credentials=(None, None),
                   receive_timeout=None):
    if bind is None:
        bind = True
    if check_names is None:
        check_names = test_check_names
    if lazy_connection is None:
        lazy_connection = test_lazy_connection
    if authentication is None:
        authentication = test_authentication
    if get_info is None:
        get_info = test_get_info
    if usage is None:
        usage = test_usage
    if fast_decoder is None:
        fast_decoder = test_fast_decoder
    if receive_timeout is None:
        receive_timeout = test_receive_timeout
    if test_server_type == 'AD' and use_ssl is None:
        use_ssl = True  # Active directory forbids Add operations in cleartext

    if test_strategy not in [MOCK_SYNC, MOCK_ASYNC]:
        # define real server
        if isinstance(test_server, (list, tuple)):
            server = ServerPool(pool_strategy=test_pooling_strategy,
                                active=test_pooling_active,
                                exhaust=test_pooling_exhaust)
            for host in test_server:
                server.add(Server(host=host,
                                  use_ssl=use_ssl,
                                  port=test_port_ssl if use_ssl else test_port,
                                  allowed_referral_hosts=('*', True),
                                  get_info=get_info,
                                  mode=test_server_mode))
        else:
            server = Server(host=test_server,
                            use_ssl=use_ssl,
                            port=test_port_ssl if use_ssl else test_port,
                            allowed_referral_hosts=('*', True),
                            get_info=get_info,
                            mode=test_server_mode)
    else:
        if test_server_type == 'EDIR':
            schema = SchemaInfo.from_json(edir_8_8_8_schema)
            info = DsaInfo.from_json(edir_8_8_8_dsa_info, schema)
            server = Server.from_definition('MockSyncServer', info, schema)
        elif test_server_type == 'AD':
            schema = SchemaInfo.from_json(ad_2012_r2_schema)
            info = DsaInfo.from_json(ad_2012_r2_dsa_info, schema)
            server = Server.from_definition('MockSyncServer', info, schema)
        elif test_server_type == 'SLAPD':
            schema = SchemaInfo.from_json(slapd_2_4_schema)
            info = DsaInfo.from_json(slapd_2_4_dsa_info, schema)
            server = Server.from_definition('MockSyncServer', info, schema)

    if authentication == SASL:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                authentication=SASL,
                                sasl_mechanism=sasl_mechanism,
                                sasl_credentials=sasl_credentials,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)
    elif authentication == NTLM:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                user=ntlm_credentials[0],
                                password=ntlm_credentials[1],
                                authentication=NTLM,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)
    elif authentication == ANONYMOUS:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                user=None,
                                password=None,
                                authentication=ANONYMOUS,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)
    else:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                user=simple_credentials[0] or test_user,
                                password=simple_credentials[1] or test_password,
                                authentication=authentication,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)

    if test_strategy in [MOCK_SYNC, MOCK_ASYNC]:
        # create authentication identities for testing mock strategies
        connection.strategy.add_entry(test_user, {'objectClass': 'inetOrgPerson', 'userPassword': test_password})
        connection.strategy.add_entry(test_secondary_user, {'objectClass': 'inetOrgPerson', 'userPassword': test_secondary_password})
        connection.strategy.add_entry(test_sasl_user_dn, {'objectClass': 'inetOrgPerson', 'userPassword': test_sasl_password})
        connection.strategy.add_entry(test_sasl_secondary_user_dn, {'objectClass': 'inetOrgPerson', 'userPassword': test_sasl_secondary_password})
        # connection.strategy.add_entry(test_ntlm_user, {'objectClass': 'inetOrgPerson', 'userPassword': test_ntlm_password})
        if bind:
            connection.bind()

    return connection
Example #34
0
from ldap3 import Server, Connection, ALL, NTLM, BASE

server = Server('10.10.10.161', get_info=ALL)

# get ROOT DSE
conn = Connection(server, auto_bind=True)
print(server.info)
conn.unbind()
"""
# get defaultNamingContext
conn = Connection(server, auto_bind=True)
print(server.info.other['dnsHostName'][0])
conn.unbind() 

# let's bind do a search to get all users and then unbind
entries = []
with Connection('htb.local', 'svc-alfresco', 's3rvice') as conn:
        conn.search('dc=htb,dc=local', '(&(objectclass=person))')
        entries = conn.entries

for entry in entries:   
    print(entry)


entries = []
with Connection('htb.local', 'svc-alfresco', 's3rvice') as conn:
    conn.search('dc=htb,dc=local', '(&(objectclass=person)(adminCount=1))', attributes=['userPrincipalName'])
    entries = conn.entries
for entry in entries:
    print(entry)
    
Example #35
0
    def authenticate(self, username=None, password=None):

        # Si el usuario tiene ldap, se ingresa por ldap
        if (self.ldap == "1"):

            try:
                sname = SERVER_HOST
                sport = SERVER_PORT
                baseDC = ROOT_DC

                # Nombre de los campos en el server LDAP
                login_field = USERNAME_FIELD
                fn_field = FIRST_NAME_FIELD
                ln_field = LAST_NAME_FIELD

                #auth_usr = '******'

                auth_usr = get_username(username)
                auth_pwd = password

                # Se buscan los 3 atributos para incluirlos en el auth_user de django
                attrnames = [login_field, ln_field, fn_field]

                s = Server(sname, port=sport, get_info=GET_SCHEMA_INFO)
                c = Connection(s,
                               auto_bind=True,
                               client_strategy=STRATEGY_SYNC,
                               user=auth_usr,
                               password=auth_pwd,
                               authentication=AUTH_SIMPLE,
                               check_names=True)
                query = '(&(objectCategory=person)(' + login_field + '=' + username.upper(
                ) + '))'
                with c:
                    c.search(baseDC,
                             query,
                             SEARCH_SCOPE_WHOLE_SUBTREE,
                             attributes=attrnames)

                # Crear usuario en auth_django sino se encuentra creado
                if c.response is not None:
                    fn = c.response[0]['attributes'][fn_field]
                    ln = c.response[0]['attributes'][ln_field]
                    user_model = get_user_model()
                    user, creado = user_model.objects.get_or_create(
                        username=username,
                        defaults={
                            'first_name': fn,
                            'last_name': ln
                        })
                    user.backend = 'Matcher_WS.backend.MyAuthBackend'

            except Exception as e:
                print(e)
                return None

            return user

        # Sino posee ldap, se chequea que la clave este correcta
        enc = 'pbkdf2_sha1$15000$' + self.salt + '$' + self.pass_field

        if (check_password(password, enc)):
            user_model = get_user_model()
            user, creado = user_model.objects.get_or_create(username=username)
            user.backend = 'Matcher_WS.backend.MyAuthBackend'
            return user

        return None