Beispiel #1
0
    def get_users(self, parameters):
        filterby = '(objectclass=user)'
        attrs = ['distinguishedName', 'objectGUID', 'objectSid', 'cn', 'accountExpires', 'adminCount',
                 'badPasswordTime', 'badPwdCount', 'description', 'displayName', 'isCriticalSystemObject',
                 'lastLogoff', 'lastLogon', 'lastLogonTimestamp', 'logonCount', 'logonHours', 'name',
                 'primaryGroupID', 'pwdLastSet', 'sAMAccountName', 'sAMAccountType', 'uSNChanged',
                 'uSNCreated', 'userAccountControl', 'whenChanged', 'whenCreated', 'memberOf', 'proxyAddresses']
        ad_help = ActiveDirectoryHelper()

        # return json object containing all user records
        results = ad_help.search(parameters, filterby, attrs)

        ldap_json = json.loads(results)

        entries = ldap_json['entries']

        for person in entries:
            attributes = person['attributes']

            groups = []
            gen_groups = []
            email_addresses = []

            for key, value in attributes.items():
                if len(value) > 0:
                    if key == 'memberOf':
                        for cn in value:
                            qs = ActiveDirectoryGroup.objects.filter(ldap_configuration=parameters,
                                                                     distinguishedName=cn)
                            for q in qs:
                                groups.append(q)
                                if q.group:
                                    gen_groups.append(q.group)
                    elif key == 'proxyAddresses':
                        for address in value:
                            email_addresses.append(address[5:])
                    else:
                        value_string = ""
                        try:
                            if isinstance(value, str):
                                value_string = value
                                value_string = value_string.decode('utf-8')
                            else:
                                for e in value:
                                    if isinstance(e, str):
                                        value_string = ''.join(e)
                                    else:
                                        value_string = e['encoded']

                            if key in ('accountExpires', 'badPasswordTime', 'lastLogoff', 'lastLogon',
                                       'lastLogonTimestamp', 'pwdLastSet', 'uSNChanged', 'uSNCreated',
                                       'whenChanged', 'whenCreated'):
                                date = self.convert_date_time(value_string)
                                if date:
                                    value_string = date.isoformat()

                            attributes[key] = value_string

                        except UnicodeDecodeError:
                            attributes[key] = self.cleanhex(value_string)

            attributes.pop('memberOf', None)
            attributes.pop('proxyAddresses', None)

            # Don't filter on everything. Start with the properties that are
            # least likely to ever change, then work towards the more mutable
            # properties.
            filter_attrs = {}
            if 'objectGUID' in attributes:
                filter_attrs['objectGUID'] = attributes['objectGUID']
            elif 'objectSid' in attributes:
                filter_attrs['objectSid'] = attributes['objectSid']
            elif 'distinguishedName' in attributes:
                filter_attrs['distinguishedName'] = attributes['distinguishedName']
            else:
                continue

            # If no matching user currently exists then create one, otherwise
            # update the existing user.
            ad_users = ActiveDirectoryUser.objects.filter(**filter_attrs)

            if ad_users.count() == 0:
                ad_user = ActiveDirectoryUser.objects.create(ldap_configuration=parameters, **attributes)
                ad_user.save()
            else:
                ad_users.update(**attributes)
                ad_user = ad_users.first()

            identity, created = Identity.objects.get_or_create(name=ad_user.displayName)
            '''
            TODO Do we need to create a person object for this identity??
            '''

            Identifier.objects.get_or_create(identifier=ad_user.sAMAccountName, identifier_type=Identifier.UNAME,
                                             identity=identity)

            # Import the email addresses.
            for email_address in email_addresses:
                Identifier.objects.get_or_create(identifier=email_address, identifier_type=Identifier.EMAIL,
                                                 identity=identity)

            for group in groups:
                print(groups)
                if ad_user.groups.filter(id=group.id).count() == 0:
                    ad_user.groups.add(group)

            for gen_group in gen_groups:
                print(gen_group.id)
                if identity.groups.filter(id=gen_group.id).count() == 0:
                    identity.groups.add(gen_group)
Beispiel #2
0
    def get_groups(self, parameters):
        filter_fields = '(objectclass=group)'
        attrs = ['distinguishedName', 'objectGUID', 'objectSid', 'cn', 'name', 'objectCategory', 'sAMAccountName']

        ad_help = ActiveDirectoryHelper()

        results = ad_help.search(parameters, filter_fields, attrs)

        ldap_json = json.loads(results)

        entries = ldap_json['entries']

        for group in entries:
            attributes = group['attributes']

            for key, value in attributes.items():

                if len(value) > 0:
                    value_string = ""
                    try:
                        if isinstance(value, str):
                            value_string = value
                            value_string = value_string.decode('utf-8')
                        else:
                            for e in value:
                                if isinstance(e, str):
                                    value_string = ''.join(e)
                                    # value_string = value_string.decode('utf-8')
                                else:
                                    value_string = e['encoded']

                        attributes[key] = value_string

                    except UnicodeDecodeError:
                        attributes[key] = self.cleanhex(value_string)

            """
            Don't filter on everything. Start with the properties that are
            least likely to ever change, then work towards the more mutable
            properties.
            """
            filter_attrs = {}
            if 'objectGUID' in attributes:
                filter_attrs['objectGUID'] = attributes['objectGUID']
            elif 'objectSid' in attributes:
                filter_attrs['objectSid'] = attributes['objectSid']
            elif 'distinguishedName' in attributes:
                filter_attrs['distinguishedName'] = attributes['distinguishedName']
            else:
                continue

            print(attributes['objectGUID'])
            print(attributes['objectSid'])
            print(attributes['distinguishedName'])

            # If no matching group currently exists then create one, otherwise
            # update the existing group.
            ad_groups = ActiveDirectoryGroup.objects.filter(**filter_attrs)
            if ad_groups.count() == 0:
                print("new group")
                ad_group = ActiveDirectoryGroup.objects.create(ldap_configuration=parameters, **attributes)

                gen_group = Group.objects.create(name=ad_group.cn, group_type=Group.AD,
                                                 description="Imported group from LDAP")
                gen_group.save()

                ad_group.group = gen_group
                ad_group.save()
            else:
                print("existing group")
                ad_groups.update(**attributes)
                ad_group = ad_groups.first()

                gen_group = ad_group.group
                if gen_group:
                    gen_group.name = ad_group.cn
                    gen_group.save()