예제 #1
0
    def entroPass(self, user, password):
        if not password:
            return None
        # 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
        try:
            pw = base64.b64decode(bytes(password,
                                        encoding='utf-8')).decode('utf-8')
        except base64.binascii.Error:
            return None

        # 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
예제 #2
0
def connect_ldap(**kwargs):
    server = Server(CONF['ldap']['host'],
                    int(CONF['ldap']['port']),
                    connect_timeout=5)
    return Connection(server, raise_exceptions=True, **kwargs)
예제 #3
0
from ldap3 import Server, Connection, ALL

server = Server('x.x.x.x', get_info=ALL)
conn = Connection(
    server,
    auto_bind=True,
    user='******',
    password='******',
)
conn.search(
    search_base='ou=users,ou=China,ou=Corp,dc=xxx,dc=xxx',
    search_filter='(&(objectclass=person)(userAccountControl=512))',
    attributes=[
        'pwdlastset',
        'userPrincipalName',
        'msDS-UserPasswordExpiryTimeComputed',
    ],
)
print(conn.entries)
예제 #4
0
 def __init__(self, secret, ldap_server, ldap_suffix='ou=People,dc=setecrs,dc=dpf,dc=gov,dc=br', check_bind=check_bind):
     self.secret = secret
     self.ldap_suffix = ldap_suffix
     self.check_bind = check_bind
     self.server = Server(ldap_server)
     self.tokens = {}
예제 #5
0
def connect(server, user, password):
    s = Server(server, get_info=ALL)
    c = Connection(s, user=user, password=password)
    c.bind()
    return c
예제 #6
0
def mock_ad_connection(password: str) -> Connection:
    """Create mock AD connection"""
    server = Server("my_fake_server", get_info=OFFLINE_AD_2012_R2)
    _pass = "******"  # noqa # nosec
    connection = Connection(
        server,
        user="******",
        password=_pass,
        client_strategy=MOCK_SYNC,
    )
    # Entry for password checking
    connection.strategy.add_entry(
        "cn=user,ou=users,dc=goauthentik,dc=io",
        {
            "name": "test-user",
            "objectSid": "unique-test-group",
            "objectClass": "person",
            "displayName": "Erin M. Hagens",
            "sAMAccountName": "sAMAccountName",
            "distinguishedName": "cn=user,ou=users,dc=goauthentik,dc=io",
        },
    )
    connection.strategy.add_entry(
        "cn=group1,ou=groups,dc=goauthentik,dc=io",
        {
            "name": "test-group",
            "objectSid": "unique-test-group",
            "objectClass": "group",
            "distinguishedName": "cn=group1,ou=groups,dc=goauthentik,dc=io",
            "member": ["cn=user0,ou=users,dc=goauthentik,dc=io"],
        },
    )
    # Group without SID
    connection.strategy.add_entry(
        "cn=group2,ou=groups,dc=goauthentik,dc=io",
        {
            "name": "test-group",
            "objectClass": "group",
            "distinguishedName": "cn=group2,ou=groups,dc=goauthentik,dc=io",
        },
    )
    connection.strategy.add_entry(
        "cn=user0,ou=users,dc=goauthentik,dc=io",
        {
            "userPassword": password,
            "sAMAccountName": "user0_sn",
            "name": "user0_sn",
            "revision": 0,
            "objectSid": "user0",
            "objectClass": "person",
            "distinguishedName": "cn=user0,ou=users,dc=goauthentik,dc=io",
            "userAccountControl": UserAccountControl.ACCOUNTDISABLE
            + UserAccountControl.NORMAL_ACCOUNT,
        },
    )
    # User without SID
    connection.strategy.add_entry(
        "cn=user1,ou=users,dc=goauthentik,dc=io",
        {
            "userPassword": "******",
            "sAMAccountName": "user2_sn",
            "name": "user1_sn",
            "revision": 0,
            "objectClass": "person",
            "distinguishedName": "cn=user1,ou=users,dc=goauthentik,dc=io",
        },
    )
    # Duplicate users
    connection.strategy.add_entry(
        "cn=user2,ou=users,dc=goauthentik,dc=io",
        {
            "userPassword": "******",
            "sAMAccountName": "user2_sn",
            "name": "user2_sn",
            "revision": 0,
            "objectSid": "unique-test2222",
            "objectClass": "person",
            "distinguishedName": "cn=user2,ou=users,dc=goauthentik,dc=io",
        },
    )
    connection.strategy.add_entry(
        "cn=user3,ou=users,dc=goauthentik,dc=io",
        {
            "userPassword": "******",
            "sAMAccountName": "user2_sn",
            "name": "user2_sn",
            "revision": 0,
            "objectSid": "unique-test2222",
            "objectClass": "person",
            "distinguishedName": "cn=user3,ou=users,dc=goauthentik,dc=io",
        },
    )
    connection.bind()
    return connection
예제 #7
0
파일: add-entity.py 프로젝트: user2595/LDAP
# import class and constants
from ldap3 import Server, Connection, ALL

# define the server

s = Server(host='yourhostname.com', port=389, use_ssl=False, get_info='ALL')

# define the connection
c = Connection(s, user='******', password='******', version=3, authentication='SIMPLE', client_strategy='SYNC', read_only=False, raise_exceptions=True)

if not c.bind():
    print('error in binding', c.result)
else:
    print('Bind is successful!!')

result = c.add(‘c=au,dc=yourhostname,dc=com’, [‘country’, ‘top’], {‘c’:’au’} )


print("Result of ADD: ",c.result)

c.unbind()

print("Unbinded successful!!")
예제 #8
0
def authorize(request):

	global session
	context={'checked':True}
	if(session!=None and session.exists('user_type')):
		if(session['user_type']=='student'):
			return redirect('/ppa/student/')
		elif(session[('user_type')]=='professor'):
			return redirect('/ppa/professor/')

	if(request.method == 'POST'):

		user_type = None
		uname = request.POST.get('username')
		pwd = request.POST.get('password')

		# if(request.POST.get('student-login')!=None):
        #
		# 	user_type = "student"
        #
		# elif(request.POST.get('admin-login')!=None):
        #
		# 	user_type = "admin"

		s = Server('ldap://ldap.iitb.ac.in', get_info=ALL)
		c = Connection(s, auto_bind=True)

		a = c.search('dc=iitb,dc=ac,dc=in', '(uid='+uname+')', )

		if(a):

			b = str(c.entries[0])
			# print(b)
			# start = b.index('uid')
			# end = b.index('in')
			user_dn = c.response[0]['dn']

			#to get dept of user

			context={'checked':True}
			info = b.split(',')
			user_dept = dept_to_short[info[2][3:]]
			if(info[1][3:] == "FAC"):
			    user_type="professor"
			elif(info[1][3:] == "UG"):
			    user_type = "student"
			elif(info[1][3:] == "PG"):
			    user_type = "student"
			elif(info[1][3:] == "DD"):
			    user_type = "student"
			else :
			    return render(request,'ppa/base_login_page.html',context)

			 

			#ending to get dept of user

			c1 = Connection(s, user_dn, pwd)

			if(not c1.bind()):
				return redirect('/ppa/login/')

			else:
				redir_url = ""
				session = SessionStore()
				if(user_type=="student"):
					u = Student.objects.filter(ldap_id=uname).first()
					redir_url = "/ppa/student/"
					if(u is None):
						u = Student(ldap_id=uname, department=user_dept, name="", email=uname+"@iitb.ac.in")
						redir_url = "/ppa/my_info/"
						u.save()
    				# commented out the following to allow changing of ldap passwords
    				# u = authenticate(username=uname, password=pwd)
					if(u is not None):
						session['user_type']=user_type
						session['ldap_id']=uname
						session.save()
						request.session['session_key'] = session.session_key
						return redirect(redir_url)
					else:
						return redirect('/ppa/login/')
				elif(user_type=="professor"):
					u = Prof.objects.filter(ldap_id=uname).first()
					redir_url = "/ppa/professor/"
					if(u is None):
						u = Prof(ldap_id=uname, department=user_dept, name="", email=uname+"@iitb.ac.in")
						redir_url = "/ppa/professor/my_info/"
						u.save()
    				# commented out the following to allow changing of ldap passwords
    				# u = authenticate(username=uname, password=pwd)
					if(u is not None):
						session['user_type']=user_type
						session['ldap_id']=uname
						session.save()
						request.session['session_key'] = session.session_key
						return redirect(redir_url)
					else:
						render(request,'ppa/base_login_page.html',context)
				else:
					render(request,'ppa/base_login_page.html',context)
		else:
			return render(request,'ppa/base_login_page.html',context)
예제 #9
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
예제 #10
0
#coding=utf-8

from ldap3 import Server, Connection, ALL, MODIFY_REPLACE, AUTO_BIND_NO_TLS
from datetime import timedelta, datetime
import openpyxl
"""
输入LDAP服务器相关信息
"""
server = Server('ldaps://192.168.26.129', get_info=ALL, use_ssl=True)
admin_username = '******'
admin_password = '******'
group_dn = 'OU=test,DC=aabbcc,DC=com'  #OU为组织单位,DC为域名拆分


def add_ad_user(add_username,
                name,
                password,
                phone,
                mail,
                user_overdue_day=30):
    """添加域账号"""
    user_dn = 'cn=%s,%s' % (add_username, group_dn)
    try:
        """创建初始化连接"""
        c = Connection(server,
                       auto_bind=True,
                       user=admin_username,
                       password=admin_password)
        """获取当前系统时间"""
        end_time = datetime.today() + timedelta(days=user_overdue_day)
        """添加用户"""
예제 #11
0
config = configparser.ConfigParser()
config.read('ldap.conf')

server = config['Main']['Server']
username = config['Main']['Username']
password = config['Main']['Password']
baseDN = config['Main']['BaseDN']
emailFile = config['Main']['EmailFile']
outputFile = config['Main']['OutputFile']
filters = config.items('SearchDN')
filterList = []
for item in filters:
    filterList.append(item[1])

s = Server(server, get_info=ALL)
c = Connection(s, user='******' + username + ',' + baseDN, password=password)

if not c.bind():
    print('error in bind', c.result)
c.start_tls()

f = open(emailFile)
emails = f.read().split('\n')
f.close

searchFilter = '(|'
for email in emails:
    searchFilter += '(proxyAddresses=smtp:' + email + ')'
searchFilter += ')'
예제 #12
0
    def init_and_get_ldap_user(self, username):
        if username is None or username == '':
            return None, None

        # add LDAP_BIND_PASSWORD as password field
        password_field = 'LDAP_BIND_PWD' if hasattr(
            settings, 'LDAP_BIND_PWD') else 'LDAP_BIND_PASSWORD'

        # check configuration
        if not (hasattr(settings, 'LDAP_SERVERS')
                and hasattr(settings, 'LDAP_BIND_USER')
                and hasattr(settings, password_field)
                and hasattr(settings, 'LDAP_SEARCH_BASE')
                and hasattr(settings, 'LDAP_USER_SEARCH_FILTER')
                and hasattr(settings, 'LDAP_ATTRIBUTES_MAP')):
            raise ImproperlyConfigured()

        # as first release of the module does not have this parameter, default is to set it true to keep the same
        # comportment after updates.
        if hasattr(settings, 'LDAP_USE_LDAP_GROUPS') and isinstance(
                settings.LDAP_USE_LDAP_GROUPS, bool):
            LDAP3ADBackend.use_groups = settings.LDAP_USE_LDAP_GROUPS
        else:
            LDAP3ADBackend.use_groups = True

        if LDAP3ADBackend.use_groups and not (
                hasattr(settings, 'LDAP_GROUPS_SEARCH_FILTER')
                and hasattr(settings, 'LDAP_GROUP_MEMBER_ATTRIBUTE')
                and hasattr(settings, 'LDAP_GROUPS_MAP')):
            raise ImproperlyConfigured()

        # LDAP_IGNORED_LOCAL_GROUPS is a list of local Django groups that must be kept.
        if (hasattr(settings, 'LDAP_IGNORED_LOCAL_GROUPS')
                and not isinstance(settings.LDAP_IGNORED_LOCAL_GROUPS, list)):
            raise ImproperlyConfigured()

        if hasattr(settings, 'LDAP_AUTHENTICATION'):
            authentication = getattr(settings, 'LDAP_AUTHENTICATION')
        else:
            authentication = SIMPLE

        # first: build server pool from settings
        if LDAP3ADBackend.pool is None:
            LDAP3ADBackend.pool = ServerPool(None,
                                             pool_strategy=FIRST,
                                             active=True)
            for srv in settings.LDAP_SERVERS:
                # from rechie, pullrequest #30
                # check if LDAP_SERVERS settings has set ldap3 `get_info` parameter
                if 'get_info' in srv:
                    server = Server(srv['host'],
                                    srv['port'],
                                    srv['use_ssl'],
                                    get_info=srv['get_info'])
                else:
                    server = Server(srv['host'], srv['port'], srv['use_ssl'])

                LDAP3ADBackend.pool.add(server)

        # then, try to connect with user/pass from settings
        con = Connection(LDAP3ADBackend.pool,
                         auto_bind=True,
                         client_strategy=SYNC,
                         user=settings.LDAP_BIND_USER,
                         password=getattr(settings, password_field)
                         or settings.LDAP_BIND_PASSWORD,
                         authentication=authentication,
                         check_names=True)

        # search for the desired user
        user_dn = None
        user_attribs = None
        con.search(settings.LDAP_SEARCH_BASE,
                   settings.LDAP_USER_SEARCH_FILTER.replace(
                       '%s', '{0}').format(username),
                   attributes=list(settings.LDAP_ATTRIBUTES_MAP.values()))
        if con.result['result'] == 0 and len(
                con.response) > 0 and 'dn' in con.response[0].keys():
            user_dn = con.response[0]['dn']
            user_attribs = con.response[0]['attributes']

            # from rechie, pullrequest #30
            # convert `user_attribs` values to string if the returned value is a list
            for attrib in user_attribs:
                if isinstance(user_attribs[attrib],
                              list) and user_attribs[attrib]:
                    user_attribs[attrib] = user_attribs[attrib][0]
                else:
                    user_attribs[attrib] = None
        con.unbind()
        return user_dn, user_attribs
예제 #13
0
    def connect(self):
        """ 
            LDAP connection method.

            Connects to an AD LDAP server via NTLM or KERBEROS authentication.
            This method supports the use of a plaintext password as well as 
            NTLM hashes.
            HASH = LMHASH:NTHASH

            Returns
            -------
            bool
                Returns the state of the connection.
        """
        logging.info('[*] Creating an LDAP connection.')
        s = Server(self._server,
                   port=self._port,
                   use_ssl=self._ssl,
                   connect_timeout=self._timeout,
                   get_info=ALL)

        if self._kerberos:
            # Use Kerberos
            logging.info('[*] Using KERBEROS authentication.')
            try:
                self._conn = Connection(s,
                                        auto_bind=AUTO_BIND_NONE,
                                        authentication=SASL,
                                        sasl_mechanism=KERBEROS,
                                        read_only=False,
                                        return_empty_attributes=True)
                bind_result = self._conn.bind()
            except Exception as e:
                msg = e.message.encode('ascii', 'ignore')
                if msg.lower(
                ).find('no kerberos credentials available (default cache: file:/tmp/'
                       ) != -1:
                    logging.error('[-] Kerberos binding error.')
                    logging.debug(
                        '[D] You need a valid kerberos TGT ticket or an LDAP TGS ticket for accessing the remote service.'
                    )
                    logging.debug(
                        '[D] Save the kerberos ticket ccache DB into /tmp/krb5cc_<uid> and try again.'
                    )
                elif msg.lower().find('ticket expired') != -1:
                    logging.error('[-] Kerberos binding error.')
                    logging.debug(
                        '[D] The provided Ticket has expired. Please provide a valid one and try again.'
                    )
                else:
                    logging.error('[-] Unexpected binding error.')
                    logging.debug('[D] Observe the following traceback:')
                    logging.debug(traceback.format_exc())
                return False
        else:
            # Use NTLM authentication
            logging.info('[*] Using NTLM authentication.')
            try:
                self._conn = Connection(s,
                                        auto_bind=AUTO_BIND_NONE,
                                        authentication=NTLM,
                                        user=self._ntuser,
                                        password=self._ntpass,
                                        read_only=False)
                bind_result = self._conn.bind()
            except:
                logging.error('[-] Unexpected binding error.')
                logging.debug('[D] Observe the following traceback:')
                logging.debug(traceback.format_exc())
                return False

        # Takes the root naming context
        if bind_result:
            self._base = json.loads(
                s.info.to_json())['raw']['rootDomainNamingContext'][0]
            logging.debug('[D] Binding base: %s' % self._base)
        else:
            logging.debug('[D] An error ocurred during the binding process.')
            logging.debug('[D] Ldap API Message: %s' %
                          self._conn.result['description'])
            return False

        return True
예제 #14
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'Domain information dumper via LDAP. Dumps users/computers/groups and OS/membership information to HTML/JSON/greppable output.'
    )
    parser._optionals.title = "Main options"
    parser._positionals.title = "Required options"

    #Main parameters
    #maingroup = parser.add_argument_group("Main options")
    parser.add_argument(
        "host",
        type=str,
        metavar='HOSTNAME',
        help=
        "Hostname/ip or ldap://host:port connection string to connect to (use ldaps:// to use SSL)"
    )
    parser.add_argument(
        "-u",
        "--user",
        type=str,
        metavar='USERNAME',
        help=
        "DOMAIN\\username for authentication, leave empty for anonymous authentication"
    )
    parser.add_argument(
        "-p",
        "--password",
        type=str,
        metavar='PASSWORD',
        help="Password or LM:NTLM hash, will prompt if not specified")
    parser.add_argument(
        "-at",
        "--authtype",
        type=str,
        choices=['NTLM', 'SIMPLE'],
        default='NTLM',
        help="Authentication type (NTLM or SIMPLE, default: NTLM)")

    #Output parameters
    outputgroup = parser.add_argument_group("Output options")
    outputgroup.add_argument(
        "-o",
        "--outdir",
        type=str,
        metavar='DIRECTORY',
        help="Directory in which the dump will be saved (default: current)")
    outputgroup.add_argument("--no-html",
                             action='store_true',
                             help="Disable HTML output")
    outputgroup.add_argument("--no-json",
                             action='store_true',
                             help="Disable JSON output")
    outputgroup.add_argument("--no-grep",
                             action='store_true',
                             help="Disable Greppable output")
    outputgroup.add_argument(
        "--grouped-json",
        action='store_true',
        default=False,
        help="Also write json files for grouped files (default: disabled)")
    outputgroup.add_argument(
        "-d",
        "--delimiter",
        help="Field delimiter for greppable output (default: tab)")

    #Additional options
    miscgroup = parser.add_argument_group("Misc options")
    miscgroup.add_argument(
        "-r",
        "--resolve",
        action='store_true',
        help=
        "Resolve computer hostnames (might take a while and cause high traffic on large networks)"
    )
    miscgroup.add_argument(
        "-n",
        "--dns-server",
        help=
        "Use custom DNS resolver instead of system DNS (try a domain controller IP)"
    )

    args = parser.parse_args()
    #Create default config
    cnf = domainDumpConfig()
    #Dns lookups?
    if args.resolve:
        cnf.lookuphostnames = True
    #Custom dns server?
    if args.dns_server is not None:
        cnf.dnsserver = args.dns_server
    #Custom separator?
    if args.delimiter is not None:
        cnf.grepsplitchar = args.delimiter
    #Disable html?
    if args.no_html:
        cnf.outputhtml = False
    #Disable json?
    if args.no_json:
        cnf.outputjson = False
    #Disable grep?
    if args.no_grep:
        cnf.outputgrep = False
    #Custom outdir?
    if args.outdir is not None:
        cnf.basepath = args.outdir
    #Do we really need grouped json files?
    cnf.groupedjson = args.grouped_json

    #Prompt for password if not set
    authentication = None
    if args.user is not None:
        if args.authtype == 'SIMPLE':
            authentication = 'SIMPLE'
        else:
            authentication = NTLM
        if not '\\' in args.user:
            log_warn('Username must include a domain, use: DOMAIN\\username')
            sys.exit(1)
        if args.password is None:
            args.password = getpass.getpass()
    else:
        log_info(
            'Connecting as anonymous user, dumping will probably fail. Consider specifying a username/password to login with'
        )
    # define the server and the connection
    s = Server(args.host, get_info=ALL)
    log_info('Connecting to host...')
    c = Connection(s,
                   user=args.user,
                   password=args.password,
                   authentication=authentication)
    log_info('Binding to host')
    # perform the Bind operation
    if not c.bind():
        log_warn('Could not bind with specified credentials')
        log_warn(c.result)
        sys.exit(1)
    log_success('Bind OK')
    log_info('Starting domain dump')
    #Create domaindumper object
    dd = domainDumper(s, c, cnf)

    #Do the actual dumping
    dd.domainDump()
    log_success('Domain dump finished')
예제 #15
0
from ldap3 import Server, Connection, ALL
from peewee import *
from api.everything import *

cfg = load_config('api/config.yaml')
# skt = load_config('api/secret_config.yaml')

theStaticDB = SqliteDatabase(cfg['databases']['static'])
theStaticDB.drop_table(LDAPFaculty)

server = Server('berea.edu', port=389, use_ssl=False, get_info='ALL')
# conn   = Connection (server, user=skt['ldap']['user'], password=skt['ldap']['pass'])
conn = Connection(server, user="******", password="******")
if not conn.bind():
    print('error in bind', conn.result)

# search_base and search_filter are the parameters
conn.search('dc=berea,dc=edu',
            '(description=Faculty)',
            attributes=['samaccountname', 'givenname', 'sn', 'employeeid'])

print("Found {0} faculty.".format(len(conn.entries)))

# print (conn.entries[0])


def safe(d, k):
    result = ""
    try:
        if k in d:
            print("Result: ", d[k])
예제 #16
0
파일: views.py 프로젝트: tashinoki/API01
 def get_ldap_server(host="", port=389):
     return Server(host, port=port, use_ssl=True)
예제 #17
0
def chat_server():
    server_socket.bind((HOST, PORT))
    server_socket.listen(10)
    # add server socket object to the list of readable connections
    SOCKET_LIST.append(server_socket)
    print("Chat server started on port " + str(PORT))
    while 1:
        # get the list sockets which are ready to be read through select
        ready_to_read, ready_to_write, in_error = select.select(
            SOCKET_LIST, [], [], 0)
        for sock in ready_to_read:
            # a new connection request recieved
            if sock == server_socket:
                sockfd, addr = server_socket.accept()
                SOCKET_LIST.append(sockfd)
                print("Client (%s, %s) connected" % addr)

            else:
                # process data recieved from client,
                # try:
                # receiving data from the socket.
                data = sock.recv(RECV_BUFFER)
                c.execute(
                    "SELECT * FROM userlist ORDER BY strftime('%Y-%m-%d %H:%M:%S',lastseen) DESC"
                )
                query = c.fetchall()
                # print(query)
                if data:
                    addr = sock.getpeername()
                    data = data.decode()
                    data = json.loads(
                        data)  #After this line data is a json object with
                    # the attribute username containing the list of receivers of the message(this is also an attribute)
                    # print(data,"dfs")
                    c.execute(
                        "SELECT username FROM userlist WHERE socketnumber = ?",
                        (sock.fileno(), ))
                    query = c.fetchall()
                    if len(query) is not 0:
                        user = query[0][0]

                    if data['action'] == "authentication":

                        s = Server(
                            "10.129.3.114", get_info=ALL
                        )  # define an unsecure LDAP server, requesting info on DSE and schema
                        name1 = data['username']
                        dnName = "cn=" + name1 + ",dc=cs252lab,dc=cse,dc=iitb,dc=ac,dc=in"
                        try:
                            con = Connection(s,
                                             dnName,
                                             data['password'],
                                             auto_bind=True)
                            con.bind()
                            msg = 'Authenticated'
                            sock.send(msg.encode())
                            #check if the user is there in the database
                            c.execute(
                                "SELECT rowid FROM userlist WHERE username = ?",
                                (data['username'], ))
                            query = c.fetchall()
                            # print(query)
                            if len(query) is 0:
                                # If user is not there in the database enter it
                                c.execute(
                                    "INSERT INTO userlist VALUES (?,?,1,?)",
                                    (data['username'], datetime.datetime.now(),
                                     sock.fileno()))
                            else:
                                # else update the online status
                                c.execute(
                                    '''UPDATE userlist SET online = ?, lastseen =?, socketnumber =? WHERE username = ? ''',
                                    (1, datetime.datetime.now(), sock.fileno(),
                                     data['username']))

                        except:
                            # print ("Your username or password is incorrect.")
                            msg = 'error'
                            sock.send(msg.encode())
                            # print('failed')
                    if data['action'] == 'exit':
                        c.execute(
                            '''UPDATE userlist SET online = ?, lastseen =?, socketnumber =? WHERE username = ? ''',
                            (0, datetime.datetime.now(), None,
                             data['username']))
                        print("Exit")
                        msg = "Done"
                        sock.send(msg.encode())
                    if data['action'] == 'main screen':
                        #Shows the messages received by the user when he was offline and info about how to get help
                        # print('main screen')
                        msg = 'Type <--help--> for help\n'
                        sock.send(msg.encode())
                        # Get the messages which were not seen by the user
                        c.execute(
                            "SELECT * FROM messagelist WHERE username = ? and seen=? ORDER BY strftime('%Y-%m-%d %H:%M:%S',sentTime) ASC",
                            (user, 0))
                        query = c.fetchall()
                        msg = ''
                        # if there are some messages then concatenate them
                        if len(query) != 0:
                            msg = msg + 'Your Previous messages are - \n'
                        #for each message convert it into proper format
                        for i in query:
                            time = i[4]
                            time_object = datetime.datetime.strptime(
                                i[4], "%Y-%m-%d %H:%M:%S.%f")
                            if time_object.strftime(
                                    "%m %d") == datetime.datetime.now(
                                    ).strftime("%m %d"):
                                time = time_object.strftime("%H:%M:%S")
                            else:
                                time = time_object.strftime("%m %d")

                            if i[3] == '':
                                msg = msg + '[M] - [' + i[
                                    2] + '] - ' + time + '\n'
                            else:
                                msg = msg + '[M] - [' + i[3] + '] - [' + i[
                                    2] + '] - ' + time + '\n'
                            msg = msg + i[5]

                        sock.send(msg.encode())
                        #update the seen status of the messages
                        c.execute("UPDATE messagelist SET seen=? WHERE seen=?",
                                  (1, 0))
                        conn.commit()

                    if data['action'] == 'send to users':
                        # print('send to users')
                        sendusers(user, data['users'], data['message'])

                    if data['action'] == 'send to groups':
                        print('send to groups')
                        sendgroups(user, data['groups'], data['message'])

                    if data['action'] == 'leave group':
                        print('leave group')
                        # Leave the group
                        msg = ''
                        for g in data['groups']:
                            # This contains the name of all the groups which the user wants to leave
                            # Get the group Id of all the groups which the user wants to leave
                            c.execute(
                                "SELECT rowid FROM grouplist WHERE groupname = ?",
                                (g, ))
                            q = c.fetchall()
                            query = []
                            for j in q:
                                query.append(j[0])

                            # print("query ",query)
                            # Check if the user is a part of those groups
                            user_group_list = []
                            for i in query:
                                c.execute(
                                    "SELECT rowid FROM group_user WHERE user_id=? and group_id = ?",
                                    (user, i))
                                rowid = c.fetchall()
                                if len(rowid) != 0:
                                    user_group_list.append(i)

                            if len(user_group_list) == 0:
                                msg = msg + 'The user does not belong to group ' + g + '\n'
                            elif len(user_group_list) == 1:
                                c.execute(
                                    "DELETE FROM group_user WHERE user_id = ? and group_id= ?",
                                    (user, user_group_list[0]))
                            else:
                                msg = msg + 'There are more than one ocurrance of ' + g + ' Choose an appropriate \n'

                        sock.send(msg.encode())

                    if data['action'] == 'add users to group':
                        c.execute(
                            "SELECT rowid FROM grouplist WHERE groupname = ?",
                            (data['group'], ))
                        #Get the group id of the group
                        q = c.fetchall()
                        # Check if the group exists
                        if (len(q) == 0):
                            msg = "Invalid Group"
                            sock.send(msg.encode())

                        else:
                            query = []
                            ## Add the group id to the list query
                            for j in q:
                                query.append(j[0])

                            #For checking if the user if a part of this group
                            user_group_list = []

                            for i in query:
                                #If the user is a part of that group only then append it to user_group_list
                                c.execute(
                                    "SELECT rowid FROM group_user WHERE user_id=? and group_id = ?",
                                    (user, i))
                                rowid = c.fetchall()
                                if len(rowid) != 0:
                                    user_group_list.append(i)

                            if len(user_group_list) == 1:
                                # Send this message to the users added
                                msg = 'You were added to the group ' + data[
                                    'group'] + ' by ' + user + '\n'
                                for i in data['users']:
                                    # Get the socket number of all the added users
                                    c.execute(
                                        "SELECT socketnumber FROM userlist WHERE username = ?",
                                        (i, ))
                                    sockno = c.fetchall()
                                    is_online = 0
                                    s = ''
                                    # check if they are online
                                    for socket in SOCKET_LIST:
                                        if sockno[0][0] == socket.fileno():
                                            s = socket
                                            is_online = 1
                                            break
                                    if is_online == 1:
                                        #If is online make the seen field one otherwise 0 and send the message to the added user
                                        c.execute(
                                            "INSERT INTO messagelist VALUES (?,?,?,?,?,?)",
                                            (i, 1, user, data['group'],
                                             datetime.datetime.now(), msg))
                                        s.send(msg.encode())
                                        c.execute(
                                            "INSERT INTO group_user VALUES (?,?,?)",
                                            (i, user_group_list[0], 0))
                                    else:
                                        #Add this to the message list
                                        c.execute(
                                            "INSERT INTO messagelist VALUES (?,?,?,?,?,?)",
                                            (i, 0, user, data['group'],
                                             datetime.datetime.now(), msg))
                                        c.execute(
                                            "INSERT INTO group_user VALUES (?,?,?)",
                                            (i, user_group_list[0], 1))

                            # send this message to the user who sent this command
                            msg = 'Added users to groups :\n'
                            for groups in user_group_list:
                                c.execute(
                                    "SELECT groupname FROM grouplist WHERE rowid = ?",
                                    (groups, ))
                                name = c.fetchall()
                                msg += name[0][0] + " "
                                msg += '\n'
                            sock.send(msg.encode())

                    if data['action'] == 'create group':
                        # print('create group')
                        for i in data['groups']:
                            # Insert the group name into the database
                            c.execute("INSERT INTO grouplist VALUES (?)",
                                      (i, ))
                            # q=c.lastrowid
                            # print("rowid of inserted",q)
                            #Insert the user into the members of the group
                            c.execute("INSERT INTO group_user VALUES (?,?,?)",
                                      (user, q, 0))
                        # send message to the user who sent this command
                        msg = 'Group created successfully\n'
                        sock.send(msg.encode())

                    if data['action'] == 'show messages group':
                        # sends the number of messages requested from the group
                        c.execute(
                            "SELECT * FROM messagelist WHERE username = ? and sentByGroup=? ORDER BY strftime('%Y-%m-%d %H:%M:%S',sentTime) DESC",
                            (user, data['group']))
                        query = c.fetchall()
                        msg = ''
                        # Check if there are any messages in the group
                        if len(query) != 0:
                            msg = msg + 'Previous messages in group ' + data[
                                'group'] + ' are - \n'
                        else:
                            msg = msg + 'There are no messages to show\n'

                        for i in range(int(data['number'])):
                            # When number of messages demanded becomes greater than the number of messages available
                            if i > len(query) - 1:
                                break
                            # Get the time stamp of the messages
                            time = query[i][4]
                            time_object = datetime.datetime.strptime(
                                query[i][4], "%Y-%m-%d %H:%M:%S.%f")
                            #Convert into proper format the time stamp
                            if time_object.strftime(
                                    "%m %d") == datetime.datetime.now(
                                    ).strftime("%m %d"):
                                time = time_object.strftime("%H:%M:%S")
                            else:
                                time = time_object.strftime("%m %d")

                            if query[i][3] == '':
                                # If the message does not belong to a group
                                msg = msg + '[M] - [' + query[i][
                                    2] + '] - ' + time + '\n'
                            else:
                                # Else the message belongs to a group
                                msg = msg + '[M] - [' + query[i][
                                    3] + '] - [' + query[i][
                                        2] + '] - ' + time + '\n'
                            msg = msg + query[i][5]

                        sock.send(msg.encode())

                    if data['action'] == 'show messages user':
                        # similar to show messages group
                        # Just shows the number of messages demanded which are sent by a specific user
                        c.execute(
                            "SELECT * FROM messagelist WHERE username = ? and sentByUser=? ORDER BY strftime('%Y-%m-%d %H:%M:%S',sentTime) DESC",
                            (user, data['user']))
                        query = c.fetchall()
                        msg = ''
                        if len(query) != 0:
                            msg = msg + 'Previous messages by user ' + data[
                                'user'] + ' are - \n'
                        else:
                            msg = msg + 'There are no messages to show\n'
                        for i in range(int(data['number'])):
                            if i > len(query) - 1:
                                break
                            time = query[i][4]
                            time_object = datetime.datetime.strptime(
                                query[i][4], "%Y-%m-%d %H:%M:%S.%f")
                            if time_object.strftime(
                                    "%m %d") == datetime.datetime.now(
                                    ).strftime("%m %d"):
                                time = time_object.strftime("%H:%M:%S")
                            else:
                                time = time_object.strftime("%m %d")

                            if query[i][3] == '':
                                msg = msg + '[M] - [' + query[i][
                                    2] + '] - ' + time + '\n'
                            else:
                                msg = msg + '[M] - [' + query[i][
                                    3] + '] - [' + query[i][
                                        2] + '] - ' + time + '\n'
                            msg = msg + query[i][5]

                        sock.send(msg.encode())

                    if data['action'] == 'show-all-users':
                        # Sends the online status of all the users
                        c.execute("SELECT * from userlist")
                        query = c.fetchall()
                        msg = ""
                        # If there are no users in the database
                        if len(query) == 0:
                            msg = "There are no users to stalk\n"
                        else:
                            msg = "The following users are/were active on the chat client\n"

                            for i in range(len(query)):

                                if query[i][0] != data['username']:

                                    if query[i][2] == 1:
                                        msg = msg + query[i][
                                            0] + " is now online\n"
                                    else:
                                        time_object = datetime.datetime.strptime(
                                            query[i][1],
                                            "%Y-%m-%d %H:%M:%S.%f")
                                        if time_object.strftime(
                                                "%m %d"
                                        ) == datetime.datetime.now().strftime(
                                                "%m %d"):
                                            time = time_object.strftime(
                                                "%H:%M:%S")
                                        else:
                                            time = time_object.strftime(
                                                "%m %d")
                                        msg = msg + query[i][
                                            0] + " was online at " + time + "\n"

                        sock.send(msg.encode())

                    if data['action'] == 'show-all-groups':
                        # sends info about all the groups that user is a part of
                        c.execute(
                            "SELECT group_id from group_user WHERE user_id = ?",
                            (data['username'], ))
                        query = c.fetchall()
                        msg = ""
                        # check if the user is a part of any group
                        if len(query) == 0:
                            msg = "You are not a part of any group\n"
                        else:
                            for i in range(len(query)):
                                c.execute(
                                    "SELECT user_id from group_user WHERE group_id = ?",
                                    (query[i][0], ))
                                # Get all the users of the group
                                query1 = c.fetchall()
                                c.execute(
                                    "SELECT groupname from grouplist WHERE rowid = ?",
                                    (query[i][0], ))
                                # Get all the group names
                                query2 = c.fetchall()

                                if len(query1) == 1:
                                    msg = msg + "Only you are part of the group " + query2[
                                        0][0] + "\n"
                                else:
                                    msg = msg + "The following members are part of the group " + query2[
                                        0][0] + "\n"

                                    for j in range(len(query1)):
                                        if query1[j][0] != data['username']:
                                            msg = msg + query1[j][0] + "\n"

                        sock.send(msg.encode())

                    if data['action'] == 'show-specific-groups':
                        # Get the group name requested
                        c.execute(
                            "SELECT rowid from grouplist WHERE groupname = ?",
                            (data['group_name'][0], ))
                        query = c.fetchall()
                        msg = ""
                        # check if the user is a part of  the group
                        if len(query) == 0:
                            msg = "You are not a part of this group\n"
                        elif len(query) >= 2:
                            # If there are requests for mutiple groups
                            # Concatenate the group ids  of the group in the message
                            msg = "You are part of the following groups:\n"
                            msg = msg + "Select the group id you wish to see with the command <--show-specific-group_id--> group_id\n"
                            for i in range(len(query)):
                                c.execute(
                                    "SELECT user_id from group_user WHERE group_id = ?",
                                    (query[i][0], ))
                                query1 = c.fetchall()
                                msg = msg + "Group id: " + str(
                                    query[i]
                                    [0]) + " and Number of users: " + str(
                                        len(query1)) + "\n"
                        else:
                            # For single group send the online status
                            c.execute(
                                "SELECT user_id from group_user WHERE group_id = ?",
                                (query[0][0], ))
                            query1 = c.fetchall()
                            count = 0
                            for i in range(len(query1)):
                                c.execute(
                                    "SELECT online from userlist WHERE username = ?",
                                    (query1[i][0], ))
                                query2 = c.fetchall()
                                if query2[0][0] == 1:
                                    count += 1
                            msg = "There are " + str(
                                count) + " users online now\n"

                        sock.send(msg.encode())

                    if data['action'] == 'show-specific-group_id':
                        # Sends the number of users online in the group now
                        c.execute(
                            "SELECT user_id from group_user WHERE group_id = ?",
                            (data['group_id'][0], ))
                        # get all the users in the group
                        query1 = c.fetchall()
                        count = 0
                        for i in range(len(query1)):
                            if query1[i][0] != data['username']:
                                c.execute(
                                    "SELECT online from userlist WHERE username = ?",
                                    (query1[i][0], ))
                                query2 = c.fetchall()
                                # for each user check if he is online
                                if query2[0][0] == 1:
                                    count += 1
                        if count > 0:
                            msg = "There are " + str(
                                count) + " users online now\n"
                        else:
                            msg = "Only you are online now\n"

                        sock.send(msg.encode())

                    if data['action'] == 'block-users':
                        # Prevents the users from sending the message to the user who request this
                        for i in data['users']:
                            # add entry to the database
                            c.execute(
                                "SELECT * FROM blocklist WHERE blockingusername = ? and blockedusername=?",
                                (user, i))
                            query = c.fetchall()
                            # check if already blocked
                            if len(query) != 0:
                                continue
                            else:
                                c.execute("INSERT INTO blocklist VALUES (?,?)",
                                          (user, i))
                                conn.commit()

                    if data['action'] == 'unblock-users':
                        for i in data['users']:
                            c.execute(
                                "SELECT * FROM blocklist WHERE blockingusername = ? and blockedusername=?",
                                (user, i))
                            query = c.fetchall()
                            if len(query) == 0:
                                continue
                            else:
                                c.execute(
                                    "DELETE FROM blocklist WHERE blockingusername = ? and blockedusername= ?",
                                    (user, i))
                                conn.commit()

                    conn.commit()

                else:
                    # remove the socket that's broken
                    c.execute(
                        '''UPDATE userlist SET online = ?,lastseen=?, socketnumber =? WHERE socketnumber = ? ''',
                        (0, datetime.datetime.now(), 0, sock.fileno()))
                    if sock in SOCKET_LIST:
                        SOCKET_LIST.remove(sock)
                    conn.commit()

    server_socket.close()
from ldap3 import Server, Connection, ALL_ATTRIBUTES, SCHEMA, SUBTREE, AUTO_BIND_NO_TLS, set_config_parameter
import argparse
import ssl
import time
import csv
import calendar

parser = argparse.ArgumentParser()
parser.add_argument("servername", type=str, help=" -> serverldap")
parser.add_argument("username", type=str, help=" -> username")
parser.add_argument("password", type=str, help=" -> password")
parser.add_argument("dnbase", type=str, help=" -> dnbase")

# Accept Self-Sign Certificates
# ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
server = Server('10.2.1.91', port=389, use_ssl=False, get_info=ALL_ATTRIBUTES)
#server = Server('10.4.1.47' ,port=389, use_ssl=False, get_info=ALL_ATTRIBUTES)
set_config_parameter('DEFAULT_CLIENT_ENCODING', 'utf8')
#BaseAD = "ou=Utilisateurs,dc=adchpg,dc=chpg,dc=mc"
BaseeDir = "O=cr"
Scope = 'SUBTREE'
#FilterAD = "(&(objectClass=person)(!(objectClass=computer)))"
FiltereDir = "(&(objectClass=group))"
#AttrsAD = ['samAccountName','cn', 'pwdLastSet','UserAccountControl','lastlogontimestamp']
AttrseDir = ['cn', 'uid', 'sn', 'givenName', 'fullName', 'LastLoginTime']
#conn = Connection(server, 'cn=Netonline,ou=Externes,ou=Utilisateurs,dc=adchpg,dc=chpg,dc=mc', 'Netonline@26', auto_bind=True)
#conn.search(search_base=BaseAD, search_filter=FilterAD, search_scope=Scope, attributes=AttrsAD )
conn = Connection(server, 'cn=admin,o=cr', 'zeus', auto_bind=True)
conn.search(search_base=BaseeDir,
            search_filter=FiltereDir,
            search_scope=Scope,
예제 #19
0
파일: test2.py 프로젝트: zh1ghest/itops
# -*- coding: utf-8 -*-
# @Time    : 2019/1/3 18:58
# @Author  :
# ad属性 安全权限相关
from ldap3 import Connection, Server, ALL, MODIFY_REPLACE
from ldap3.protocol.microsoft import security_descriptor_control

from apps.securitytab import ldaptypes
from apps.securitytab.uuids import string_to_bin

ldap3RESTARTABLE = Connection(server=Server('', get_info=ALL, use_ssl=False),
                              user='******',
                              password='',
                              auto_bind=True)


def test():
    try:
        # Set SD flags to only query for DACL设置SD标志仅查询DACL
        controls = security_descriptor_control(sdflags=0x04)
        ldap3RESTARTABLE.search(
            'DC=,DC=com',
            '(&(objectClass=user)(SAMAccountName=sdfsd112))',
            attributes=['SAMAccountName', 'nTSecurityDescriptor', 'objectSid'],
            controls=controls)
        entry = ldap3RESTARTABLE.entries[0]
        usersid = entry['objectSid'].value
        print(usersid)
        secDescData = entry['nTSecurityDescriptor'].raw_values[0]  # 默认权限
        secDesc = ldaptypes.SR_SECURITY_DESCRIPTOR(data=secDescData)
        everyone = create_every_ace()
예제 #20
0
def ldap_get_all_users_spn(AttackParameters, port):
    # build DN
    DN = "DC=" + ",DC=".join(AttackParameters.realm.split('.'))

    # Kerberos authentication
    if AttackParameters.auth_gssapi:
        WRITE_STDOUT(G + "\nConnecting to " + B + '\'' + AttackParameters.DC_addr \
                    + '\'' + W + G + " using ldap protocol and"\
                    + " Kerberos authentication!\n" + W)

        WRITE_STDOUT('  [+] Creating ticket ccache file %r...' % ccache_file)
        cc = CCache((AttackParameters.realm, AttackParameters.user_account))
        tgt_cred = kdc_rep2ccache(AttackParameters.as_data["as_rep"],
                                  AttackParameters.as_data["as_rep_enc"])
        cc.add_credential(tgt_cred)
        cc.save(ccache_file)
        WRITE_STDOUT(' Done!\n')

        WRITE_STDOUT('  [+] Initiating ldap connection using ticket...')
        server = ldap3.Server(AttackParameters.DC_addr)
        c = ldap3.Connection(server,
                             authentication=ldap3.SASL,
                             sasl_mechanism='GSSAPI')
        WRITE_STDOUT(' Done!\n')

    # NTLM authentication
    else:
        WRITE_STDOUT(G + "Connecting to " + B + '\'' + AttackParameters.DC_addr + '\'' + W +\
                         G + " using ldap protocol and NTLM authentication!\n" + W)

        s = Server(AttackParameters.DC_addr, port=389, get_info=ALL)

        c = Connection(s,
                       auto_bind=False,
                       client_strategy=SYNC,
                       user=AttackParameters.realm + "\\" +
                       AttackParameters.user_account,
                       password=AttackParameters.password,
                       authentication=NTLM,
                       check_names=True)

    # Now we should be connected to the DC through LDAP
    try:
        c.open()
    except ldap3.core.exceptions.LDAPSocketOpenError as e:
        WRITE_STDOUT(R + "ldap connection error: %s\n" % e + W)
        sys.exit(1)

    try:
        r = c.bind()
    except:
        WRITE_STDOUT(R + "Cannot connect to ldap, exiting.\n" + W)
        sys.exit(1)

    # Query to find all accounts having a servicePrincipalName
    attributes_to_retrieve = [x.lower() for x in ATTRIBUTES_TO_RETRIEVE]

    c.search(DN,
             LDAP_QUERY,
             search_scope='SUBTREE',
             attributes=attributes_to_retrieve)

    if not c.response:
        WRITE_STDOUT(R + "Cannot find any SPN, wrong user/credentials?\n" + W)
        sys.exit(1)

    WRITE_STDOUT('  [+] Retrieving all SPN and corresponding accounts...')

    # construct path to SPN_outfile to store LDAP response
    if AttackParameters.outputfile_path != None:
        outputfile_spn = ""
        dirname = os.path.dirname(AttackParameters.outputfile_path)
        # current dir
        if dirname == '':
            dirname = './'
        else:
            dirname = dirname + '/'
        filename = os.path.basename(AttackParameters.outputfile_path)
        filename = 'SPN_' + filename
        outputfile_spn = open(dirname + filename, 'w')

    # iterate through results to construc dico[{'attribute':'value'},{}, etc.] for each "{}" account
    dico_users_spn = []
    for matching_object in c.response:
        if matching_object.has_key('attributes'):
            dico_account = {}
            for attribute, value in matching_object['attributes'].items():
                # delimiter of SPN is ';' in AD but ',' using ldap3 structures
                if attribute.lower(
                ) == "serviceprincipalname" and len(attribute) > 1:
                    # only need one SPN for the attack
                    value = value[0]
                if attribute.lower() in attributes_to_retrieve:
                    if type(value) is int:
                        dico_account[attribute.encode("utf8").lower()] = str(
                            value)
                    else:
                        value = "".join(value).encode("utf8")
                        dico_account[attribute.encode(
                            "utf8").lower()] = value.lower()
            dico_users_spn.append(dico_account)

    # Disconnecting from DC
    WRITE_STDOUT(' Done!\n')
    c.unbind()
    WRITE_STDOUT(G + "Successfully disconnected from "+ B + '\''\
                 + AttackParameters.DC_addr + '\'\n' + W)

    # write to SPN_outputfile
    if AttackParameters.outputfile_path != None:
        for accounts in dico_users_spn:
            line_to_write = accounts['samaccountname']+'$'\
                            +accounts['serviceprincipalname']
            if accounts.has_key('memberof'):
                line_to_write = line_to_write + '$' + accounts['memberof']
            if accounts.has_key('primarygroupid'):
                line_to_write = line_to_write + '$primaryGroupID:'\
                                + accounts['primarygroupid']
            outputfile_spn.write(line_to_write + '\n')
        outputfile_spn.close()

    return dico_users_spn
def login(username: str, password: str) -> tuple:
    """
    Connect to LDAP server, perform a search and attempt a bind.

    Can raise `exc.LDAPConnectionError` exceptions if the
    connection to LDAP fails.

    Can raise `exc.LDAPUserLoginError` exceptions if the
    login to LDAP fails.

    :returns: tuple (username, email, full_name)

    """

    tls = None
    if TLS_CERTS:
        tls = TLS_CERTS

    # connect to the LDAP server
    if SERVER.lower().startswith("ldaps://"):
        use_ssl = True
    else:
        use_ssl = False
    try:
        server = Server(SERVER, port=PORT, get_info=NONE,
                        use_ssl=use_ssl, tls=tls)
    except Exception as e:
        error = "Error connecting to LDAP server: %s" % e
        raise LDAPConnectionError({"error_message": error})

    # authenticate as service if credentials provided, anonymously otherwise
    if BIND_DN is not None and BIND_DN != '':
        service_user = BIND_DN
        service_pass = BIND_PASSWORD
        service_auth = SIMPLE
    else:
        service_user = None
        service_pass = None
        service_auth = ANONYMOUS

    auto_bind = AUTO_BIND_NO_TLS
    if START_TLS:
        auto_bind = AUTO_BIND_TLS_BEFORE_BIND

    try:
        c = Connection(server, auto_bind=auto_bind, client_strategy=SYNC, check_names=True,
                       user=service_user, password=service_pass, authentication=service_auth)
    except Exception as e:
        error = "Error connecting to LDAP server: %s" % e
        raise LDAPConnectionError({"error_message": error})

    # search for user-provided login
    search_filter = '(|(%s=%s)(%s=%s))' % (
        USERNAME_ATTRIBUTE, username, EMAIL_ATTRIBUTE, username)
    if SEARCH_FILTER_ADDITIONAL:
        search_filter = '(&%s%s)' % (search_filter, SEARCH_FILTER_ADDITIONAL)
    try:
        c.search(search_base=SEARCH_BASE,
                 search_filter=search_filter,
                 search_scope=SUBTREE,
                 attributes=[USERNAME_ATTRIBUTE,
                             EMAIL_ATTRIBUTE, FULL_NAME_ATTRIBUTE],
                 paged_size=5)
    except Exception as e:
        error = "LDAP login incorrect: %s" % e
        raise LDAPUserLoginError({"error_message": error})

    # we are only interested in user objects in the response
    c.response = [r for r in c.response if 'raw_attributes' in r and 'dn' in r]
    # stop if no search results
    if not c.response:
        raise LDAPUserLoginError({"error_message": "LDAP login not found"})

    # handle multiple matches
    if len(c.response) > 1:
        raise LDAPUserLoginError(
            {"error_message": "LDAP login could not be determined."})

    # handle missing mandatory attributes
    raw_attributes = c.response[0].get('raw_attributes')
    #if raw_attributes.get(USERNAME_ATTRIBUTE) or raw_attributes.get(EMAIL_ATTRIBUTE) or raw_attributes.get(FULL_NAME_ATTRIBUTE):
    #    raise LDAPUserLoginError({"error_message": "LDAP login is invalid."})

    # attempt LDAP bind
    username = raw_attributes.get(USERNAME_ATTRIBUTE)[0].decode('utf-8')
    email = raw_attributes.get(EMAIL_ATTRIBUTE)[0].decode('utf-8')
    full_name = raw_attributes.get(FULL_NAME_ATTRIBUTE)[0].decode('utf-8')
    try:
        dn = str(bytes(c.response[0].get('dn'), 'utf-8'), encoding='utf-8')
        Connection(server, auto_bind=auto_bind, client_strategy=SYNC,
                   check_names=True, authentication=SIMPLE,
                   user=dn, password=password)
    except Exception as e:
        error = "LDAP bind failed: %s" % e
        raise LDAPUserLoginError({"error_message": error})

    # LDAP binding successful, but some values might have changed, or
    # this is the user's first login, so return them
    return (username, email, full_name)
예제 #22
0
Move the outputs of the script to the fixtures directory to run them with the newuser test suite.

https://ldap3.readthedocs.io/mocking.html#a-complete-example
"""
import json
from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, MOCK_SYNC

INFO_OUTPUT = "csua_ldap_info.json"
SCHEMA_OUTPUT = "csua_ldap_schema.json"
ENTRIES_OUTPUT = "csua_ldap_entries.json"

if __name__ == "__main__":
    REAL_SERVER = "ldaps://ldap.csua.berkeley.edu"

    # Retrieve server info and schema from a real server
    server = Server(REAL_SERVER, get_info=ALL)
    connection = Connection(server, auto_bind=True)

    # Store server info and schema to json files
    server.info.to_file(INFO_OUTPUT)
    server.schema.to_file(SCHEMA_OUTPUT)

    # Read entries from a portion of the DIT from real server and store them in a json file
    if connection.search("dc=csua,dc=berkeley,dc=edu",
                         "(objectclass=*)",
                         attributes=ALL_ATTRIBUTES):
        raw_entries = connection.response_to_json(raw=True)
        entries = json.loads(raw_entries)
        filtered_entries = {
            "entries": [
                i for i in entries["entries"]
예제 #23
0
from config import db
from blueprints.users import users
from ldap3.utils.hashed import hashed
from blueprints.bluedocker import bdocker
from ldap3 import Server, Connection, HASHED_MD5
from flask import Flask, render_template, flash, redirect, request, jsonify, session

app = Flask(__name__)
app.register_blueprint(users)
app.register_blueprint(bdocker)
app.secret_key = 'flask-app'

server = Server('ldap://127.0.0.1:389')
DN = 'cn=admin,dc=dexter,dc=com,dc=br'


@app.route('/')
def index():
    if 'auth' in session:
        return redirect('/users')
    return render_template('index.html')


@app.route('/login', methods=['POST'])
def login():
    data = request.form
    dn = 'mail={0},dc=dexter,dc=com,dc=br'.format(data['email'])
    ldap = Connection(server, dn, data['senha'])
    if ldap.bind():
        session['auth'] = True
        return redirect('/users')
예제 #24
0
파일: base.py 프로젝트: bbrk364/eNMS
 def init_ldap_client(self):
     self.ldap_client = Server(self.settings["ldap"]["server"],
                               get_info=ALL)
예제 #25
0
    get_deleted_user_entries,
    get_role_id_from_cn,
    get_role,
    get_role_admins,
    get_role_members,
    get_role_owners,
    get_user_in_db_by_email,
    get_user_mapping_entry,
    get_user_metadata_entry,
    get_user_next_id,
    get_pack_owners_by_user,
    is_user_in_db,
    is_group_in_db,
)

SERVER = Server("my_fake_server", get_info=OFFLINE_AD_2012_R2)

# ------------------------------------------------------------------------------
# <==== BEGIN TEST PARAMETERS =================================================>
# ------------------------------------------------------------------------------

TEST_USERS = [
    {
        "common_name": "User0",
        "name": "Zeroth User",
        "given_name": "Zeroth"
    },
    {
        "common_name": "User1",
        "name": "First User",
        "given_name": "First"
예제 #26
0
# -*- coding:utf-8 -*-
from ldap3 import Server, Connection

server = Server(host='ldap://10.211.254.49', port=10389)
conn = Connection(server,
                  user='******',
                  password='******',
                  auto_bind=True,
                  read_only=True,
                  auto_referrals=False)

# Setting ldap.OPT_REFERRALS to 0 tells the server not to "chase" referrals, i.e. not to resolve them
print(server.info)

# bind
# dn = "uid=admin,ou=system"
# pw = "secret"
# conn = ldap.initialize("ldap://10.211.254.49:10389")
# conn.simple_bind_s(dn, pw)
#
# conn.set_option(ldap.OPT_REFERRALS, 0)
# conn.protocol_version = ldap.VERSION3
#
# for entry in conn.search_s(
#         'uid=liuyangc3,ou=developer,dc=nxin,dc=com',
#         scope=ldap.SCOPE_SUBTREE):
#     print(entry)
예제 #27
0
 def __init__(self, plugin):
     self.server = Server(plugin.host,
                          port=plugin.port,
                          use_ssl=plugin.use_ssl)
     self.bind_dn = plugin.bind_dn
     self.password = plugin.bind_password
예제 #28
0
def users_dosync(request):
    """ Выполнение синхронизации с LDAP """
    from ldap3 import Server, Connection, SIMPLE, SYNC, ALL_ATTRIBUTES, SUBTREE, ALL
    from laboratory import settings

    result = {}

    s = Server(settings.LDAP["server"]["host"],
               port=settings.LDAP["server"]["port"],
               get_info=ALL)
    c = Connection(s,
                   auto_bind=True,
                   user=settings.LDAP["server"]["user"],
                   password=settings.LDAP["server"]["password"],
                   client_strategy=SYNC,
                   authentication=SIMPLE,
                   check_names=True)

    result_t = ""

    groups = {}
    c.search(search_base=settings.LDAP["base"],
             search_filter='(&(objectClass=person))',
             search_scope=SUBTREE,
             attributes=ALL_ATTRIBUTES,
             get_operational_attributes=True)
    resp = json.loads(c.response_to_json())
    i = 0
    for ldap_user in resp["entries"]:
        if "uidNumber" not in ldap_user["attributes"].keys() or "uid" not in ldap_user[
            "attributes"].keys() or "userPassword" not in ldap_user["attributes"].keys() or "displayName" not in \
                ldap_user["attributes"].keys():
            continue

        if Podrazdeleniya.objects.filter(
                gid_n=int(ldap_user["attributes"]["gidNumber"])).exists():
            pod = Podrazdeleniya.objects.get(
                gid_n=int(ldap_user["attributes"]["gidNumber"]))
            pod.title = ldap_user["attributes"]["ou"][0]
            pod.save()
        else:
            pod = Podrazdeleniya(title=ldap_user["attributes"]["ou"][0],
                                 gid_n=int(
                                     ldap_user["attributes"]["gidNumber"]))
            pod.save()

        i += 1
        active = False
        if ldap_user["attributes"]["accountStatus"] == "active":
            active = True
        dn = ldap_user["attributes"]["displayName"]

        username = ldap_user["attributes"]["uid"][0]
        password = ldap_user["attributes"]["userPassword"][0]

        if not User.objects.filter(username=username).exists(
        ):  # Проверка существования пользователя
            user = User.objects.create_user(username)  # Создание пользователя
            user.set_password(password)  # Установка пароля
            user.is_active = active
            user.save()  # Сохранение пользователя

            profile = DoctorProfile.objects.create()  # Создание профиля
            profile.user = user  # Привязка профиля к пользователю
            profile.podrazileniye = pod

            profile.labtype = 0
            if "врач" in emp or "зав" in emp:
                profile.labtype = 1
            elif "лаб" in emp or "лаборант" in emp:
                profile.labtype = 2
        else:
            user = User.objects.get(username=username)
            user.set_password(password)
            user.is_active = active
            user.save()
            profile = DoctorProfile.objects.get(user=user)
        emp = ldap_user["attributes"]["employeeType"][0].lower()
        profile.isLDAP_user = True
        profile.fio = dn
        profile.save()
    c.unbind()
    return HttpResponse(json.dumps(groups), content_type="application/json")
예제 #29
0
    def authenticate(self,
                     request,
                     username=None,
                     password=None,
                     **keyword_arguments):

        # Check for remote user in extra arguments if no username and password.
        # In case of basic authentication
        if not username or not password:
            if 'remote_user' in keyword_arguments:
                credentials = base_64_decode_basic_auth(
                    keyword_arguments['remote_user'])
                if credentials:
                    username, password = credentials[0], credentials[1]
                else:
                    return None
            else:
                return None

        user = check_user_exists_and_active(self, username)

        is_authenticated_with_ldap = False
        errors = []
        for server in settings.LDAP_SERVERS:
            try:
                port = server.get('port', 636)
                use_ssl = server.get('use_ssl', True)
                bind_as_authentication = server.get('bind_as_authentication',
                                                    True)
                domain = server.get('domain')
                t = Tls(validate=CERT_REQUIRED,
                        version=PROTOCOL_TLSv1_2,
                        ca_certs_file=server.get('certificate'))
                s = Server(server['url'], port=port, use_ssl=use_ssl, tls=t)
                auto_bind = AUTO_BIND_TLS_BEFORE_BIND if use_ssl else AUTO_BIND_NO_TLS
                ldap_bind_user = f"{domain}\\{username}" if domain else username
                if not bind_as_authentication:
                    # binding to LDAP first, then search for user
                    bind_username = server.get('bind_username', None)
                    bind_username = f"{domain}\\{bind_username}" if domain and bind_username else bind_username
                    bind_password = server.get('bind_password', None)
                    authentication = SIMPLE if bind_username and bind_password else ANONYMOUS
                    c = Connection(s,
                                   user=bind_username,
                                   password=bind_password,
                                   auto_bind=auto_bind,
                                   authentication=authentication,
                                   raise_exceptions=True)
                    search_username_field = server.get('search_username_field',
                                                       'uid')
                    search_attribute = server.get('search_attribute', 'cn')
                    search = c.search(server['base_dn'],
                                      f"({search_username_field}={username})",
                                      attributes=[search_attribute])
                    if not search or search_attribute not in c.response[0].get(
                            'attributes', []):
                        # no results, unbind and continue to next server
                        c.unbind()
                        errors.append(
                            f"User {username} attempted to authenticate with LDAP ({server['url']}), but the search with dn:{server['base_dn']}, username_field:{search_username_field} and attribute:{search_attribute} did not return any results. The user was denied access"
                        )
                        continue
                    else:
                        # we got results, get the dn that will be used for binding authentication
                        response = c.response[0]
                        ldap_bind_user = response['dn']
                        c.unbind()

                # let's proceed with binding using the user trying to authenticate
                c = Connection(s,
                               user=ldap_bind_user,
                               password=password,
                               auto_bind=auto_bind,
                               authentication=SIMPLE,
                               raise_exceptions=True)
                c.unbind()
                # At this point the user successfully authenticated to at least one LDAP server.
                is_authenticated_with_ldap = True
                auth_logger.debug(
                    f"User {username} was successfully authenticated with LDAP ({server['url']})"
                )
                break
            except LDAPBindError as e:
                errors.append(
                    f"User {username} attempted to authenticate with LDAP ({server['url']}), but entered an incorrect password. The user was denied access: {str(e)}"
                )
            except LDAPException as e:
                errors.append(
                    f"User {username} attempted to authenticate with LDAP ({server['url']}), but an error occurred. The user was denied access: {str(e)}"
                )

        if is_authenticated_with_ldap:
            return user
        else:
            for error in errors:
                auth_logger.warning(error)
            return None
예제 #30
0
def ldap_conn(username, password):
    s = Server(config.Config.LDAP_HOST)
    user = '******'.format(username)
    conn = Connection(s, user=user, password=password)
    return conn