test_ntlm_user = '******' test_ntlm_password = '******' test_logging_filename = join(gettempdir(), 'ldap3.log') test_valid_names = ['sl10.intra.camera.it'] else: raise Exception('testing location ' + location + ' is not valid') if test_logging: try: remove(test_logging_filename) except OSError: pass import logging logging.basicConfig(filename=test_logging_filename, level=logging.DEBUG) set_library_log_detail_level(test_log_detail) print('Testing location:', location) print('Test server:', test_server) print('Python version:', version) print('Strategy:', test_strategy, '- Lazy:', test_lazy_connection, '- Check names:', test_check_names, '- Collect usage:', test_usage) print('Logging:', 'False' if not test_logging else test_logging_filename, '- Log detail:', get_detail_level_name(test_log_detail) if test_logging else 'None') def random_id(): return '[' + str(SystemRandom().random())[-8:] + ']' def generate_dn(base, batch_id, name): return test_name_attr + '=' + batch_id + name + ',' + base
script d'envoie de user dans LDAP """ VERSION = 0.2 import logging logging.basicConfig(filename='client_application.log', level=logging.DEBUG) from ldap3 import Server, Connection, SUBTREE from ldap3.utils.log import set_library_log_detail_level, OFF, BASIC, NETWORK, EXTENDED, PROTOCOL import argparse import mods.ldap set_library_log_detail_level(BASIC) server='ldap-130a' dn_connect='cn=admin,dc=edelia,dc=net' dn_pass='******' con='' users={} #pp.get_users() #exit() LDAP_USER_BRANCH='ou=people,dc=edelia,dc=net'
from ldap3 import NTLM from ldap3.utils.log import set_library_log_detail_level, EXTENDED # Core Django imports from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ # Third-party app imports # Imports from your apps from apps.Core.models import CommonModel logger = logging.getLogger(__name__) set_library_log_detail_level(EXTENDED) # Create your models here. class DomainSetting(CommonModel): fqdn = models.CharField(max_length=128, verbose_name=_("(Fully Qualified Domain Name)完全合格域名"), unique=True) NetBIOS = models.CharField(max_length=24, verbose_name=_("NetBios name"), unique=True) dc_server = models.CharField(max_length=24, verbose_name=_("DC Server Name/IP"), unique=True) search_base = models.TextField(verbose_name=_("搜索限定"), default="dc=home,dc=local") connect_user = models.CharField(max_length=128, verbose_name=_("连接用户名")) connect_pass = models.CharField(max_length=128, verbose_name=_("连接密码")) def __unicode__(self): return self.NetBIOS
else: test_strategy = SYNC # sync strategy for executing tests # test_strategy = ASYNC # uncomment this line to test the async strategy # test_strategy = RESTARTABLE # uncomment this line to test the sync_restartable strategy # test_strategy = REUSABLE # uncomment this line to test the sync_reusable_threaded strategy test_lazy_connection = False # connection lazy if test_logging: try: remove(test_logging_filename) except OSError: pass import logging logging.basicConfig(filename=test_logging_filename, level=logging.DEBUG) set_library_log_detail_level(test_log_detail) print('Testing location:', location) print('Test server:', test_server) print('Python version:', version) print('Strategy:', test_strategy, '- Lazy:', test_lazy_connection, '- Check names:', test_check_names, '- Collect usage:', test_usage) print('Logging:', 'False' if not test_logging else test_logging_filename, '- Log detail:', get_detail_level_name(test_log_detail) if test_logging else 'None') def random_id(): return '[' + str(SystemRandom().random())[-8:] + ']'
def main(): ''' INSTANCE CONFIGURATION ''' SERVER_IP = demisto.params().get('server_ip') USERNAME = demisto.params().get('credentials')['identifier'] PASSWORD = demisto.params().get('credentials')['password'] DEFAULT_BASE_DN = demisto.params().get('base_dn') SECURE_CONNECTION = demisto.params().get('secure_connection') DEFAULT_PAGE_SIZE = int(demisto.params().get('page_size')) NTLM_AUTH = demisto.params().get('ntlm') UNSECURE = demisto.params().get('unsecure', False) PORT = demisto.params().get('port') if PORT: # port was configured, cast to int PORT = int(PORT) last_log_detail_level = None try: try: set_library_log_hide_sensitive_data(True) if is_debug_mode(): demisto.info( 'debug-mode: setting library log detail to EXTENDED') last_log_detail_level = get_library_log_detail_level() set_library_log_detail_level(EXTENDED) server = initialize_server(SERVER_IP, PORT, SECURE_CONNECTION, UNSECURE) except Exception as e: return_error(str(e)) return global conn if NTLM_AUTH: # intialize connection to LDAP server with NTLM authentication # user example: domain\user domain_user = SERVER_IP + '\\' + USERNAME if '\\' not in USERNAME else USERNAME conn = Connection(server, user=domain_user, password=PASSWORD, authentication=NTLM) else: # here username should be the user dn conn = Connection(server, user=USERNAME, password=PASSWORD) # bind operation is the “authenticate” operation. try: # open socket and bind to server if not conn.bind(): message = "Failed to bind to server. Please validate the credentials configured correctly.\n{}".format( json.dumps(conn.result)) return_error(message) return except Exception as e: exc_msg = str(e) demisto.info("Failed bind to: {}:{}. {}: {}".format( SERVER_IP, PORT, type(e), exc_msg + "\nTrace:\n{}".format(traceback.format_exc()))) message = "Failed to access LDAP server. Please validate the server host and port are configured correctly" if 'ssl wrapping error' in exc_msg: message = "Failed to access LDAP server. SSL error." if not UNSECURE: message += ' Try using: "Trust any certificate" option.' return_error(message) return demisto.info('Established connection with AD LDAP server') if not base_dn_verified(DEFAULT_BASE_DN): message = "Failed to verify the base DN configured for the instance.\n" \ "Last connection result: {}\n" \ "Last error from LDAP server: {}".format(json.dumps(conn.result), json.dumps(conn.last_error)) return_error(message) return demisto.info('Verfied base DN "{}"'.format(DEFAULT_BASE_DN)) ''' COMMAND EXECUTION ''' if demisto.command() == 'test-module': if conn.user == '': # Empty response means you have no authentication status on the server, so you are an anonymous user. raise Exception("Failed to authenticate user") demisto.results('ok') if demisto.command() == 'ad-search': free_search(DEFAULT_BASE_DN, DEFAULT_PAGE_SIZE) if demisto.command() == 'ad-expire-password': expire_user_password(DEFAULT_BASE_DN) if demisto.command() == 'ad-set-new-password': set_user_password(DEFAULT_BASE_DN) if demisto.command() == 'ad-unlock-account': unlock_account(DEFAULT_BASE_DN) if demisto.command() == 'ad-disable-account': disable_user(DEFAULT_BASE_DN) if demisto.command() == 'ad-enable-account': enable_user(DEFAULT_BASE_DN) if demisto.command() == 'ad-remove-from-group': remove_member_from_group(DEFAULT_BASE_DN) if demisto.command() == 'ad-add-to-group': add_member_to_group(DEFAULT_BASE_DN) if demisto.command() == 'ad-create-user': create_user() if demisto.command() == 'ad-delete-user': delete_user() if demisto.command() == 'ad-update-user': update_user(DEFAULT_BASE_DN) if demisto.command() == 'ad-modify-computer-ou': modify_computer_ou(DEFAULT_BASE_DN) if demisto.command() == 'ad-create-contact': create_contact() if demisto.command() == 'ad-update-contact': update_contact() if demisto.command() == 'ad-get-user': search_users(DEFAULT_BASE_DN, DEFAULT_PAGE_SIZE) if demisto.command() == 'ad-get-computer': search_computers(DEFAULT_BASE_DN, DEFAULT_PAGE_SIZE) if demisto.command() == 'ad-get-group-members': search_group_members(DEFAULT_BASE_DN, DEFAULT_PAGE_SIZE) except Exception as e: message = str(e) if conn: message += "\nLast connection result: {}\nLast error from LDAP server: {}".format( json.dumps(conn.result), conn.last_error) return_error(message) return finally: # disconnect and close the connection if conn: conn.unbind() if last_log_detail_level: set_library_log_detail_level(last_log_detail_level)
from classes.config import Config, ConfigErrorException from classes.ldap import Ldap, LdapErrorException, TestFailedException from ldap3.utils.log import set_library_log_detail_level, set_library_log_activation_level, OFF, BASIC, NETWORK, EXTENDED try: config = Config() except ConfigErrorException as e: print("ERROR: Configuration error: {} ".format(e)) quit() if config.args.log: logging.basicConfig(filename='ldap.log', level=logging.DEBUG) set_library_log_activation_level(logging.DEBUG) set_library_log_detail_level(EXTENDED) try: ldap = Ldap(config=config) ldap.run_test() except LdapErrorException as e: print("ERROR: {}".format(e)) quit() except TestFailedException as e: print("FAILED") print(e) quit() print("OK") quit()
import json from logging import basicConfig from logging.config import dictConfig from os.path import isfile from urllib.parse import urlparse import connexion import yaml from connexion import ProblemException from flask import current_app as app from flask.json import JSONEncoder from ipa.model import JsonMixin from ldap3 import ALL, Connection, Server # TODO: use connection pool from ldap3.utils.log import EXTENDED, NETWORK, set_library_log_detail_level set_library_log_detail_level(NETWORK) def configure_logger(log_config="logging.yaml"): """Configure the logging subsystem.""" if not isfile(log_config): return basicConfig() set_library_log_detail_level(NETWORK) return with open(log_config) as fh: log_config = yaml.load(fh) return dictConfig(log_config) def connect3(host, user, password):
from ldap3.protocol.rfc4511 import ( LDAPMessage, MessageID, ProtocolOp, BindRequest, Version, AuthenticationChoice, Simple, BindResponse, ResultCode, SearchResultDone, SearchResultEntry, LDAPDN, PartialAttributeList, PartialAttribute, AttributeDescription, Vals, AttributeValue) from ldap3.strategy.sync import SyncStrategy from pyasn1.codec.ber.encoder import encode from pyasn1.codec.ber.decoder import decode from ldap3.utils import log logging.basicConfig(level=logging.DEBUG) log.set_library_log_activation_level(logging.DEBUG) log.set_library_log_detail_level(log.EXTENDED) class Connection(object): def __init__(self, socket): self.socket = socket def receive(sock, message_id=None): conn = Connection(socket=sock) raw_messages = SyncStrategy(ldap_connection=conn).receiving() messages = [] for r in raw_messages: ldap_resp, _ = decode(r, asn1Spec=LDAPMessage()) i = ldap_resp['messageID']