Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connection.py 76KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501
  1. """
  2. """
  3. # Created on 2014.05.31
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2014 - 2018 Giovanni Cannata
  8. #
  9. # This file is part of ldap3.
  10. #
  11. # ldap3 is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU Lesser General Public License as published
  13. # by the Free Software Foundation, either version 3 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # ldap3 is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU Lesser General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU Lesser General Public License
  22. # along with ldap3 in the COPYING and COPYING.LESSER files.
  23. # If not, see <http://www.gnu.org/licenses/>.
  24. from copy import deepcopy
  25. from os import linesep
  26. from threading import RLock, Lock
  27. from functools import reduce
  28. import json
  29. from .. import ANONYMOUS, SIMPLE, SASL, MODIFY_ADD, MODIFY_DELETE, MODIFY_REPLACE, get_config_parameter, DEREF_ALWAYS, \
  30. SUBTREE, ASYNC, SYNC, NO_ATTRIBUTES, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, MODIFY_INCREMENT, LDIF, ASYNC_STREAM, \
  31. RESTARTABLE, ROUND_ROBIN, REUSABLE, AUTO_BIND_NONE, AUTO_BIND_TLS_BEFORE_BIND, AUTO_BIND_TLS_AFTER_BIND, AUTO_BIND_NO_TLS, \
  32. STRING_TYPES, SEQUENCE_TYPES, MOCK_SYNC, MOCK_ASYNC, NTLM, EXTERNAL, DIGEST_MD5, GSSAPI, PLAIN
  33. from .results import RESULT_SUCCESS, RESULT_COMPARE_TRUE, RESULT_COMPARE_FALSE
  34. from ..extend import ExtendedOperationsRoot
  35. from .pooling import ServerPool
  36. from .server import Server
  37. from ..operation.abandon import abandon_operation, abandon_request_to_dict
  38. from ..operation.add import add_operation, add_request_to_dict
  39. from ..operation.bind import bind_operation, bind_request_to_dict
  40. from ..operation.compare import compare_operation, compare_request_to_dict
  41. from ..operation.delete import delete_operation, delete_request_to_dict
  42. from ..operation.extended import extended_operation, extended_request_to_dict
  43. from ..operation.modify import modify_operation, modify_request_to_dict
  44. from ..operation.modifyDn import modify_dn_operation, modify_dn_request_to_dict
  45. from ..operation.search import search_operation, search_request_to_dict
  46. from ..protocol.rfc2849 import operation_to_ldif, add_ldif_header
  47. from ..protocol.sasl.digestMd5 import sasl_digest_md5
  48. from ..protocol.sasl.external import sasl_external
  49. from ..protocol.sasl.plain import sasl_plain
  50. from ..strategy.sync import SyncStrategy
  51. from ..strategy.mockAsync import MockAsyncStrategy
  52. from ..strategy.asynchronous import AsyncStrategy
  53. from ..strategy.reusable import ReusableStrategy
  54. from ..strategy.restartable import RestartableStrategy
  55. from ..strategy.ldifProducer import LdifProducerStrategy
  56. from ..strategy.mockSync import MockSyncStrategy
  57. from ..strategy.asyncStream import AsyncStreamStrategy
  58. from ..operation.unbind import unbind_operation
  59. from ..protocol.rfc2696 import paged_search_control
  60. from .usage import ConnectionUsage
  61. from .tls import Tls
  62. from .exceptions import LDAPUnknownStrategyError, LDAPBindError, LDAPUnknownAuthenticationMethodError, \
  63. LDAPSASLMechanismNotSupportedError, LDAPObjectClassError, LDAPConnectionIsReadOnlyError, LDAPChangeError, LDAPExceptionError, \
  64. LDAPObjectError, LDAPSocketReceiveError, LDAPAttributeError, LDAPInvalidValueError, LDAPConfigurationError
  65. from ..utils.conv import escape_bytes, prepare_for_stream, check_json_dict, format_json, to_unicode
  66. from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, EXTENDED, get_library_log_hide_sensitive_data
  67. from ..utils.dn import safe_dn
  68. SASL_AVAILABLE_MECHANISMS = [EXTERNAL,
  69. DIGEST_MD5,
  70. GSSAPI,
  71. PLAIN]
  72. CLIENT_STRATEGIES = [SYNC,
  73. ASYNC,
  74. LDIF,
  75. RESTARTABLE,
  76. REUSABLE,
  77. MOCK_SYNC,
  78. MOCK_ASYNC,
  79. ASYNC_STREAM]
  80. def _format_socket_endpoint(endpoint):
  81. if endpoint and len(endpoint) == 2: # IPv4
  82. return str(endpoint[0]) + ':' + str(endpoint[1])
  83. elif endpoint and len(endpoint) == 4: # IPv6
  84. return '[' + str(endpoint[0]) + ']:' + str(endpoint[1])
  85. try:
  86. return str(endpoint)
  87. except Exception:
  88. return '?'
  89. def _format_socket_endpoints(sock):
  90. if sock:
  91. try:
  92. local = sock.getsockname()
  93. except Exception:
  94. local = (None, None, None, None)
  95. try:
  96. remote = sock.getpeername()
  97. except Exception:
  98. remote = (None, None, None, None)
  99. return '<local: ' + _format_socket_endpoint(local) + ' - remote: ' + _format_socket_endpoint(remote) + '>'
  100. return '<no socket>'
  101. # noinspection PyProtectedMember
  102. class Connection(object):
  103. """Main ldap connection class.
  104. Controls, if used, must be a list of tuples. Each tuple must have 3
  105. elements, the control OID, a boolean meaning if the control is
  106. critical, a value.
  107. If the boolean is set to True the server must honor the control or
  108. refuse the operation
  109. Mixing controls must be defined in controls specification (as per
  110. RFC 4511)
  111. :param server: the Server object to connect to
  112. :type server: Server, str
  113. :param user: the user name for simple authentication
  114. :type user: str
  115. :param password: the password for simple authentication
  116. :type password: str
  117. :param auto_bind: specify if the bind will be performed automatically when defining the Connection object
  118. :type auto_bind: int, can be one of AUTO_BIND_NONE, AUTO_BIND_NO_TLS, AUTO_BIND_TLS_BEFORE_BIND, AUTO_BIND_TLS_AFTER_BIND as specified in ldap3
  119. :param version: LDAP version, default to 3
  120. :type version: int
  121. :param authentication: type of authentication
  122. :type authentication: int, can be one of AUTH_ANONYMOUS, AUTH_SIMPLE or AUTH_SASL, as specified in ldap3
  123. :param client_strategy: communication strategy used in the Connection
  124. :type client_strategy: can be one of STRATEGY_SYNC, STRATEGY_ASYNC_THREADED, STRATEGY_LDIF_PRODUCER, STRATEGY_SYNC_RESTARTABLE, STRATEGY_REUSABLE_THREADED as specified in ldap3
  125. :param auto_referrals: specify if the connection object must automatically follow referrals
  126. :type auto_referrals: bool
  127. :param sasl_mechanism: mechanism for SASL authentication, can be one of 'EXTERNAL', 'DIGEST-MD5', 'GSSAPI', 'PLAIN'
  128. :type sasl_mechanism: str
  129. :param sasl_credentials: credentials for SASL mechanism
  130. :type sasl_credentials: tuple
  131. :param check_names: if True the library will check names of attributes and object classes against the schema. Also values found in entries will be formatted as indicated by the schema
  132. :type check_names: bool
  133. :param collect_usage: collect usage metrics in the usage attribute
  134. :type collect_usage: bool
  135. :param read_only: disable operations that modify data in the LDAP server
  136. :type read_only: bool
  137. :param lazy: open and bind the connection only when an actual operation is performed
  138. :type lazy: bool
  139. :param raise_exceptions: raise exceptions when operations are not successful, if False operations return False if not successful but not raise exceptions
  140. :type raise_exceptions: bool
  141. :param pool_name: pool name for pooled strategies
  142. :type pool_name: str
  143. :param pool_size: pool size for pooled strategies
  144. :type pool_size: int
  145. :param pool_lifetime: pool lifetime for pooled strategies
  146. :type pool_lifetime: int
  147. :param use_referral_cache: keep referral connections open and reuse them
  148. :type use_referral_cache: bool
  149. :param auto_escape: automatic escaping of filter values
  150. :param auto_encode: automatic encoding of attribute values
  151. :type use_referral_cache: bool
  152. """
  153. def __init__(self,
  154. server,
  155. user=None,
  156. password=None,
  157. auto_bind=AUTO_BIND_NONE,
  158. version=3,
  159. authentication=None,
  160. client_strategy=SYNC,
  161. auto_referrals=True,
  162. auto_range=True,
  163. sasl_mechanism=None,
  164. sasl_credentials=None,
  165. check_names=True,
  166. collect_usage=False,
  167. read_only=False,
  168. lazy=False,
  169. raise_exceptions=False,
  170. pool_name=None,
  171. pool_size=None,
  172. pool_lifetime=None,
  173. fast_decoder=True,
  174. receive_timeout=None,
  175. return_empty_attributes=True,
  176. use_referral_cache=False,
  177. auto_escape=True,
  178. auto_encode=True,
  179. pool_keepalive=None):
  180. conf_default_pool_name = get_config_parameter('DEFAULT_THREADED_POOL_NAME')
  181. self.connection_lock = RLock() # re-entrant lock to ensure that operations in the Connection object are executed atomically in the same thread
  182. with self.connection_lock:
  183. if client_strategy not in CLIENT_STRATEGIES:
  184. self.last_error = 'unknown client connection strategy'
  185. if log_enabled(ERROR):
  186. log(ERROR, '%s for <%s>', self.last_error, self)
  187. raise LDAPUnknownStrategyError(self.last_error)
  188. self.strategy_type = client_strategy
  189. self.user = user
  190. self.password = password
  191. if not authentication and self.user:
  192. self.authentication = SIMPLE
  193. elif not authentication:
  194. self.authentication = ANONYMOUS
  195. elif authentication in [SIMPLE, ANONYMOUS, SASL, NTLM]:
  196. self.authentication = authentication
  197. else:
  198. self.last_error = 'unknown authentication method'
  199. if log_enabled(ERROR):
  200. log(ERROR, '%s for <%s>', self.last_error, self)
  201. raise LDAPUnknownAuthenticationMethodError(self.last_error)
  202. self.version = version
  203. self.auto_referrals = True if auto_referrals else False
  204. self.request = None
  205. self.response = None
  206. self.result = None
  207. self.bound = False
  208. self.listening = False
  209. self.closed = True
  210. self.last_error = None
  211. if auto_bind is False: # compatibility with older version where auto_bind was a boolean
  212. self.auto_bind = AUTO_BIND_NONE
  213. elif auto_bind is True:
  214. self.auto_bind = AUTO_BIND_NO_TLS
  215. else:
  216. self.auto_bind = auto_bind
  217. self.sasl_mechanism = sasl_mechanism
  218. self.sasl_credentials = sasl_credentials
  219. self._usage = ConnectionUsage() if collect_usage else None
  220. self.socket = None
  221. self.tls_started = False
  222. self.sasl_in_progress = False
  223. self.read_only = read_only
  224. self._context_state = []
  225. self._deferred_open = False
  226. self._deferred_bind = False
  227. self._deferred_start_tls = False
  228. self._bind_controls = None
  229. self._executing_deferred = False
  230. self.lazy = lazy
  231. self.pool_name = pool_name if pool_name else conf_default_pool_name
  232. self.pool_size = pool_size
  233. self.pool_lifetime = pool_lifetime
  234. self.pool_keepalive = pool_keepalive
  235. self.starting_tls = False
  236. self.check_names = check_names
  237. self.raise_exceptions = raise_exceptions
  238. self.auto_range = True if auto_range else False
  239. self.extend = ExtendedOperationsRoot(self)
  240. self._entries = []
  241. self.fast_decoder = fast_decoder
  242. self.receive_timeout = receive_timeout
  243. self.empty_attributes = return_empty_attributes
  244. self.use_referral_cache = use_referral_cache
  245. self.auto_escape = auto_escape
  246. self.auto_encode = auto_encode
  247. if isinstance(server, STRING_TYPES):
  248. server = Server(server)
  249. if isinstance(server, SEQUENCE_TYPES):
  250. server = ServerPool(server, ROUND_ROBIN, active=True, exhaust=True)
  251. if isinstance(server, ServerPool):
  252. self.server_pool = server
  253. self.server_pool.initialize(self)
  254. self.server = self.server_pool.get_current_server(self)
  255. else:
  256. self.server_pool = None
  257. self.server = server
  258. # if self.authentication == SIMPLE and self.user and self.check_names:
  259. # self.user = safe_dn(self.user)
  260. # if log_enabled(EXTENDED):
  261. # log(EXTENDED, 'user name sanitized to <%s> for simple authentication via <%s>', self.user, self)
  262. if self.strategy_type == SYNC:
  263. self.strategy = SyncStrategy(self)
  264. elif self.strategy_type == ASYNC:
  265. self.strategy = AsyncStrategy(self)
  266. elif self.strategy_type == LDIF:
  267. self.strategy = LdifProducerStrategy(self)
  268. elif self.strategy_type == RESTARTABLE:
  269. self.strategy = RestartableStrategy(self)
  270. elif self.strategy_type == REUSABLE:
  271. self.strategy = ReusableStrategy(self)
  272. self.lazy = False
  273. elif self.strategy_type == MOCK_SYNC:
  274. self.strategy = MockSyncStrategy(self)
  275. elif self.strategy_type == MOCK_ASYNC:
  276. self.strategy = MockAsyncStrategy(self)
  277. elif self.strategy_type == ASYNC_STREAM:
  278. self.strategy = AsyncStreamStrategy(self)
  279. else:
  280. self.last_error = 'unknown strategy'
  281. if log_enabled(ERROR):
  282. log(ERROR, '%s for <%s>', self.last_error, self)
  283. raise LDAPUnknownStrategyError(self.last_error)
  284. # maps strategy functions to connection functions
  285. self.send = self.strategy.send
  286. self.open = self.strategy.open
  287. self.get_response = self.strategy.get_response
  288. self.post_send_single_response = self.strategy.post_send_single_response
  289. self.post_send_search = self.strategy.post_send_search
  290. if not self.strategy.no_real_dsa:
  291. self.do_auto_bind()
  292. # else: # for strategies with a fake server set get_info to NONE if server hasn't a schema
  293. # if self.server and not self.server.schema:
  294. # self.server.get_info = NONE
  295. if log_enabled(BASIC):
  296. if get_library_log_hide_sensitive_data():
  297. log(BASIC, 'instantiated Connection: <%s>', self.repr_with_sensitive_data_stripped())
  298. else:
  299. log(BASIC, 'instantiated Connection: <%r>', self)
  300. def do_auto_bind(self):
  301. if self.auto_bind and self.auto_bind != AUTO_BIND_NONE:
  302. if log_enabled(BASIC):
  303. log(BASIC, 'performing automatic bind for <%s>', self)
  304. if self.closed:
  305. self.open(read_server_info=False)
  306. if self.auto_bind == AUTO_BIND_NO_TLS:
  307. self.bind(read_server_info=True)
  308. elif self.auto_bind == AUTO_BIND_TLS_BEFORE_BIND:
  309. self.start_tls(read_server_info=False)
  310. self.bind(read_server_info=True)
  311. elif self.auto_bind == AUTO_BIND_TLS_AFTER_BIND:
  312. self.bind(read_server_info=False)
  313. self.start_tls(read_server_info=True)
  314. if not self.bound:
  315. self.last_error = 'automatic bind not successful' + (' - ' + self.last_error if self.last_error else '')
  316. if log_enabled(ERROR):
  317. log(ERROR, '%s for <%s>', self.last_error, self)
  318. raise LDAPBindError(self.last_error)
  319. def __str__(self):
  320. s = [
  321. str(self.server) if self.server else 'None',
  322. 'user: ' + str(self.user),
  323. 'lazy' if self.lazy else 'not lazy',
  324. 'unbound' if not self.bound else ('deferred bind' if self._deferred_bind else 'bound'),
  325. 'closed' if self.closed else ('deferred open' if self._deferred_open else 'open'),
  326. _format_socket_endpoints(self.socket),
  327. 'tls not started' if not self.tls_started else('deferred start_tls' if self._deferred_start_tls else 'tls started'),
  328. 'listening' if self.listening else 'not listening',
  329. self.strategy.__class__.__name__ if hasattr(self, 'strategy') else 'No strategy',
  330. 'internal decoder' if self.fast_decoder else 'pyasn1 decoder'
  331. ]
  332. return ' - '.join(s)
  333. def __repr__(self):
  334. conf_default_pool_name = get_config_parameter('DEFAULT_THREADED_POOL_NAME')
  335. if self.server_pool:
  336. r = 'Connection(server={0.server_pool!r}'.format(self)
  337. else:
  338. r = 'Connection(server={0.server!r}'.format(self)
  339. r += '' if self.user is None else ', user={0.user!r}'.format(self)
  340. r += '' if self.password is None else ', password={0.password!r}'.format(self)
  341. r += '' if self.auto_bind is None else ', auto_bind={0.auto_bind!r}'.format(self)
  342. r += '' if self.version is None else ', version={0.version!r}'.format(self)
  343. r += '' if self.authentication is None else ', authentication={0.authentication!r}'.format(self)
  344. r += '' if self.strategy_type is None else ', client_strategy={0.strategy_type!r}'.format(self)
  345. r += '' if self.auto_referrals is None else ', auto_referrals={0.auto_referrals!r}'.format(self)
  346. r += '' if self.sasl_mechanism is None else ', sasl_mechanism={0.sasl_mechanism!r}'.format(self)
  347. r += '' if self.sasl_credentials is None else ', sasl_credentials={0.sasl_credentials!r}'.format(self)
  348. r += '' if self.check_names is None else ', check_names={0.check_names!r}'.format(self)
  349. r += '' if self.usage is None else (', collect_usage=' + ('True' if self.usage else 'False'))
  350. r += '' if self.read_only is None else ', read_only={0.read_only!r}'.format(self)
  351. r += '' if self.lazy is None else ', lazy={0.lazy!r}'.format(self)
  352. r += '' if self.raise_exceptions is None else ', raise_exceptions={0.raise_exceptions!r}'.format(self)
  353. r += '' if (self.pool_name is None or self.pool_name == conf_default_pool_name) else ', pool_name={0.pool_name!r}'.format(self)
  354. r += '' if self.pool_size is None else ', pool_size={0.pool_size!r}'.format(self)
  355. r += '' if self.pool_lifetime is None else ', pool_lifetime={0.pool_lifetime!r}'.format(self)
  356. r += '' if self.pool_keepalive is None else ', pool_keepalive={0.pool_keepalive!r}'.format(self)
  357. r += '' if self.fast_decoder is None else (', fast_decoder=' + ('True' if self.fast_decoder else 'False'))
  358. r += '' if self.auto_range is None else (', auto_range=' + ('True' if self.auto_range else 'False'))
  359. r += '' if self.receive_timeout is None else ', receive_timeout={0.receive_timeout!r}'.format(self)
  360. r += '' if self.empty_attributes is None else (', return_empty_attributes=' + ('True' if self.empty_attributes else 'False'))
  361. r += '' if self.auto_encode is None else (', auto_encode=' + ('True' if self.auto_encode else 'False'))
  362. r += '' if self.auto_escape is None else (', auto_escape=' + ('True' if self.auto_escape else 'False'))
  363. r += '' if self.use_referral_cache is None else (', use_referral_cache=' + ('True' if self.use_referral_cache else 'False'))
  364. r += ')'
  365. return r
  366. def repr_with_sensitive_data_stripped(self):
  367. conf_default_pool_name = get_config_parameter('DEFAULT_THREADED_POOL_NAME')
  368. if self.server_pool:
  369. r = 'Connection(server={0.server_pool!r}'.format(self)
  370. else:
  371. r = 'Connection(server={0.server!r}'.format(self)
  372. r += '' if self.user is None else ', user={0.user!r}'.format(self)
  373. r += '' if self.password is None else ", password='{0}'".format('<stripped %d characters of sensitive data>' % len(self.password))
  374. r += '' if self.auto_bind is None else ', auto_bind={0.auto_bind!r}'.format(self)
  375. r += '' if self.version is None else ', version={0.version!r}'.format(self)
  376. r += '' if self.authentication is None else ', authentication={0.authentication!r}'.format(self)
  377. r += '' if self.strategy_type is None else ', client_strategy={0.strategy_type!r}'.format(self)
  378. r += '' if self.auto_referrals is None else ', auto_referrals={0.auto_referrals!r}'.format(self)
  379. r += '' if self.sasl_mechanism is None else ', sasl_mechanism={0.sasl_mechanism!r}'.format(self)
  380. if self.sasl_mechanism == DIGEST_MD5:
  381. r += '' if self.sasl_credentials is None else ", sasl_credentials=({0!r}, {1!r}, '{2}', {3!r})".format(self.sasl_credentials[0], self.sasl_credentials[1], '*' * len(self.sasl_credentials[2]), self.sasl_credentials[3])
  382. else:
  383. r += '' if self.sasl_credentials is None else ', sasl_credentials={0.sasl_credentials!r}'.format(self)
  384. r += '' if self.check_names is None else ', check_names={0.check_names!r}'.format(self)
  385. r += '' if self.usage is None else (', collect_usage=' + 'True' if self.usage else 'False')
  386. r += '' if self.read_only is None else ', read_only={0.read_only!r}'.format(self)
  387. r += '' if self.lazy is None else ', lazy={0.lazy!r}'.format(self)
  388. r += '' if self.raise_exceptions is None else ', raise_exceptions={0.raise_exceptions!r}'.format(self)
  389. r += '' if (self.pool_name is None or self.pool_name == conf_default_pool_name) else ', pool_name={0.pool_name!r}'.format(self)
  390. r += '' if self.pool_size is None else ', pool_size={0.pool_size!r}'.format(self)
  391. r += '' if self.pool_lifetime is None else ', pool_lifetime={0.pool_lifetime!r}'.format(self)
  392. r += '' if self.pool_keepalive is None else ', pool_keepalive={0.pool_keepalive!r}'.format(self)
  393. r += '' if self.fast_decoder is None else (', fast_decoder=' + 'True' if self.fast_decoder else 'False')
  394. r += '' if self.auto_range is None else (', auto_range=' + ('True' if self.auto_range else 'False'))
  395. r += '' if self.receive_timeout is None else ', receive_timeout={0.receive_timeout!r}'.format(self)
  396. r += '' if self.empty_attributes is None else (', return_empty_attributes=' + 'True' if self.empty_attributes else 'False')
  397. r += '' if self.auto_encode is None else (', auto_encode=' + ('True' if self.auto_encode else 'False'))
  398. r += '' if self.auto_escape is None else (', auto_escape=' + ('True' if self.auto_escape else 'False'))
  399. r += '' if self.use_referral_cache is None else (', use_referral_cache=' + ('True' if self.use_referral_cache else 'False'))
  400. r += ')'
  401. return r
  402. @property
  403. def stream(self):
  404. """Used by the LDIFProducer strategy to accumulate the ldif-change operations with a single LDIF header
  405. :return: reference to the response stream if defined in the strategy.
  406. """
  407. return self.strategy.get_stream() if self.strategy.can_stream else None
  408. @stream.setter
  409. def stream(self, value):
  410. with self.connection_lock:
  411. if self.strategy.can_stream:
  412. self.strategy.set_stream(value)
  413. @property
  414. def usage(self):
  415. """Usage statistics for the connection.
  416. :return: Usage object
  417. """
  418. if not self._usage:
  419. return None
  420. if self.strategy.pooled: # update master connection usage from pooled connections
  421. self._usage.reset()
  422. for worker in self.strategy.pool.workers:
  423. self._usage += worker.connection.usage
  424. self._usage += self.strategy.pool.terminated_usage
  425. return self._usage
  426. def __enter__(self):
  427. with self.connection_lock:
  428. self._context_state.append((self.bound, self.closed)) # save status out of context as a tuple in a list
  429. if self.closed:
  430. self.open()
  431. if not self.bound:
  432. self.bind()
  433. return self
  434. # noinspection PyUnusedLocal
  435. def __exit__(self, exc_type, exc_val, exc_tb):
  436. with self.connection_lock:
  437. context_bound, context_closed = self._context_state.pop()
  438. if (not context_bound and self.bound) or self.stream: # restore status prior to entering context
  439. try:
  440. self.unbind()
  441. except LDAPExceptionError:
  442. pass
  443. if not context_closed and self.closed:
  444. self.open()
  445. if exc_type is not None:
  446. if log_enabled(ERROR):
  447. log(ERROR, '%s for <%s>', exc_type, self)
  448. return False # re-raise LDAPExceptionError
  449. def bind(self,
  450. read_server_info=True,
  451. controls=None):
  452. """Bind to ldap Server with the authentication method and the user defined in the connection
  453. :param read_server_info: reads info from server
  454. :param controls: LDAP controls to send along with the bind operation
  455. :type controls: list of tuple
  456. :return: bool
  457. """
  458. if log_enabled(BASIC):
  459. log(BASIC, 'start BIND operation via <%s>', self)
  460. self.last_error = None
  461. with self.connection_lock:
  462. if self.lazy and not self._executing_deferred:
  463. if self.strategy.pooled:
  464. self.strategy.validate_bind(controls)
  465. self._deferred_bind = True
  466. self._bind_controls = controls
  467. self.bound = True
  468. if log_enabled(BASIC):
  469. log(BASIC, 'deferring bind for <%s>', self)
  470. else:
  471. self._deferred_bind = False
  472. self._bind_controls = None
  473. if self.closed: # try to open connection if closed
  474. self.open(read_server_info=False)
  475. if self.authentication == ANONYMOUS:
  476. if log_enabled(PROTOCOL):
  477. log(PROTOCOL, 'performing anonymous BIND for <%s>', self)
  478. if not self.strategy.pooled:
  479. request = bind_operation(self.version, self.authentication, self.user, '', auto_encode=self.auto_encode)
  480. if log_enabled(PROTOCOL):
  481. log(PROTOCOL, 'anonymous BIND request <%s> sent via <%s>', bind_request_to_dict(request), self)
  482. response = self.post_send_single_response(self.send('bindRequest', request, controls))
  483. else:
  484. response = self.strategy.validate_bind(controls) # only for REUSABLE
  485. elif self.authentication == SIMPLE:
  486. if log_enabled(PROTOCOL):
  487. log(PROTOCOL, 'performing simple BIND for <%s>', self)
  488. if not self.strategy.pooled:
  489. request = bind_operation(self.version, self.authentication, self.user, self.password, auto_encode=self.auto_encode)
  490. if log_enabled(PROTOCOL):
  491. log(PROTOCOL, 'simple BIND request <%s> sent via <%s>', bind_request_to_dict(request), self)
  492. response = self.post_send_single_response(self.send('bindRequest', request, controls))
  493. else:
  494. response = self.strategy.validate_bind(controls) # only for REUSABLE
  495. elif self.authentication == SASL:
  496. if self.sasl_mechanism in SASL_AVAILABLE_MECHANISMS:
  497. if log_enabled(PROTOCOL):
  498. log(PROTOCOL, 'performing SASL BIND for <%s>', self)
  499. if not self.strategy.pooled:
  500. response = self.do_sasl_bind(controls)
  501. else:
  502. response = self.strategy.validate_bind(controls) # only for REUSABLE
  503. else:
  504. self.last_error = 'requested SASL mechanism not supported'
  505. if log_enabled(ERROR):
  506. log(ERROR, '%s for <%s>', self.last_error, self)
  507. raise LDAPSASLMechanismNotSupportedError(self.last_error)
  508. elif self.authentication == NTLM:
  509. if self.user and self.password and len(self.user.split('\\')) == 2:
  510. if log_enabled(PROTOCOL):
  511. log(PROTOCOL, 'performing NTLM BIND for <%s>', self)
  512. if not self.strategy.pooled:
  513. response = self.do_ntlm_bind(controls)
  514. else:
  515. response = self.strategy.validate_bind(controls) # only for REUSABLE
  516. else: # user or password missing
  517. self.last_error = 'NTLM needs domain\\username and a password'
  518. if log_enabled(ERROR):
  519. log(ERROR, '%s for <%s>', self.last_error, self)
  520. raise LDAPUnknownAuthenticationMethodError(self.last_error)
  521. else:
  522. self.last_error = 'unknown authentication method'
  523. if log_enabled(ERROR):
  524. log(ERROR, '%s for <%s>', self.last_error, self)
  525. raise LDAPUnknownAuthenticationMethodError(self.last_error)
  526. if not self.strategy.sync and not self.strategy.pooled and self.authentication not in (SASL, NTLM): # get response if asynchronous except for SASL and NTLM that return the bind result even for asynchronous strategy
  527. _, result = self.get_response(response)
  528. if log_enabled(PROTOCOL):
  529. log(PROTOCOL, 'async BIND response id <%s> received via <%s>', result, self)
  530. elif self.strategy.sync:
  531. result = self.result
  532. if log_enabled(PROTOCOL):
  533. log(PROTOCOL, 'BIND response <%s> received via <%s>', result, self)
  534. elif self.strategy.pooled or self.authentication in (SASL, NTLM): # asynchronous SASL and NTLM or reusable strtegy get the bind result synchronously
  535. result = response
  536. else:
  537. self.last_error = 'unknown authentication method'
  538. if log_enabled(ERROR):
  539. log(ERROR, '%s for <%s>', self.last_error, self)
  540. raise LDAPUnknownAuthenticationMethodError(self.last_error)
  541. if result is None:
  542. # self.bound = True if self.strategy_type == REUSABLE else False
  543. self.bound = False
  544. elif result is True:
  545. self.bound = True
  546. elif result is False:
  547. self.bound = False
  548. else:
  549. self.bound = True if result['result'] == RESULT_SUCCESS else False
  550. if not self.bound and result and result['description'] and not self.last_error:
  551. self.last_error = result['description']
  552. if read_server_info and self.bound:
  553. self.refresh_server_info()
  554. self._entries = []
  555. if log_enabled(BASIC):
  556. log(BASIC, 'done BIND operation, result <%s>', self.bound)
  557. return self.bound
  558. def rebind(self,
  559. user=None,
  560. password=None,
  561. authentication=None,
  562. sasl_mechanism=None,
  563. sasl_credentials=None,
  564. read_server_info=True,
  565. controls=None
  566. ):
  567. if log_enabled(BASIC):
  568. log(BASIC, 'start (RE)BIND operation via <%s>', self)
  569. self.last_error = None
  570. with self.connection_lock:
  571. if user:
  572. self.user = user
  573. if password is not None:
  574. self.password = password
  575. if not authentication and user:
  576. self.authentication = SIMPLE
  577. if authentication in [SIMPLE, ANONYMOUS, SASL, NTLM]:
  578. self.authentication = authentication
  579. elif authentication is not None:
  580. self.last_error = 'unknown authentication method'
  581. if log_enabled(ERROR):
  582. log(ERROR, '%s for <%s>', self.last_error, self)
  583. raise LDAPUnknownAuthenticationMethodError(self.last_error)
  584. if sasl_mechanism:
  585. self.sasl_mechanism = sasl_mechanism
  586. if sasl_credentials:
  587. self.sasl_credentials = sasl_credentials
  588. # if self.authentication == SIMPLE and self.user and self.check_names:
  589. # self.user = safe_dn(self.user)
  590. # if log_enabled(EXTENDED):
  591. # log(EXTENDED, 'user name sanitized to <%s> for rebind via <%s>', self.user, self)
  592. if not self.strategy.pooled:
  593. try:
  594. return self.bind(read_server_info, controls)
  595. except LDAPSocketReceiveError:
  596. raise LDAPBindError('Unable to rebind as a different user, furthermore the server abruptly closed the connection')
  597. else:
  598. self.strategy.pool.rebind_pool()
  599. return True
  600. def unbind(self,
  601. controls=None):
  602. """Unbind the connected user. Unbind implies closing session as per RFC4511 (4.3)
  603. :param controls: LDAP controls to send along with the bind operation
  604. """
  605. if log_enabled(BASIC):
  606. log(BASIC, 'start UNBIND operation via <%s>', self)
  607. if self.use_referral_cache:
  608. self.strategy.unbind_referral_cache()
  609. self.last_error = None
  610. with self.connection_lock:
  611. if self.lazy and not self._executing_deferred and (self._deferred_bind or self._deferred_open): # _clear deferred status
  612. self.strategy.close()
  613. self._deferred_open = False
  614. self._deferred_bind = False
  615. self._deferred_start_tls = False
  616. elif not self.closed:
  617. request = unbind_operation()
  618. if log_enabled(PROTOCOL):
  619. log(PROTOCOL, 'UNBIND request sent via <%s>', self)
  620. self.send('unbindRequest', request, controls)
  621. self.strategy.close()
  622. if log_enabled(BASIC):
  623. log(BASIC, 'done UNBIND operation, result <%s>', True)
  624. return True
  625. def search(self,
  626. search_base,
  627. search_filter,
  628. search_scope=SUBTREE,
  629. dereference_aliases=DEREF_ALWAYS,
  630. attributes=None,
  631. size_limit=0,
  632. time_limit=0,
  633. types_only=False,
  634. get_operational_attributes=False,
  635. controls=None,
  636. paged_size=None,
  637. paged_criticality=False,
  638. paged_cookie=None,
  639. auto_escape=None):
  640. """
  641. Perform an ldap search:
  642. - If attributes is empty noRFC2696 with the specified size
  643. - If paged is 0 and cookie is present the search is abandoned on
  644. server attribute is returned
  645. - If attributes is ALL_ATTRIBUTES all attributes are returned
  646. - If paged_size is an int greater than 0 a simple paged search
  647. is tried as described in
  648. - Cookie is an opaque string received in the last paged search
  649. and must be used on the next paged search response
  650. - If lazy == True open and bind will be deferred until another
  651. LDAP operation is performed
  652. - If mssing_attributes == True then an attribute not returned by the server is set to None
  653. - If auto_escape is set it overrides the Connection auto_escape
  654. """
  655. conf_attributes_excluded_from_check = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_CHECK')]
  656. if log_enabled(BASIC):
  657. log(BASIC, 'start SEARCH operation via <%s>', self)
  658. if self.check_names and search_base:
  659. search_base = safe_dn(search_base)
  660. if log_enabled(EXTENDED):
  661. log(EXTENDED, 'search base sanitized to <%s> for SEARCH operation via <%s>', search_base, self)
  662. with self.connection_lock:
  663. self._fire_deferred()
  664. if not attributes:
  665. attributes = [NO_ATTRIBUTES]
  666. elif attributes == ALL_ATTRIBUTES:
  667. attributes = [ALL_ATTRIBUTES]
  668. if isinstance(attributes, STRING_TYPES):
  669. attributes = [attributes]
  670. if get_operational_attributes and isinstance(attributes, list):
  671. attributes.append(ALL_OPERATIONAL_ATTRIBUTES)
  672. elif get_operational_attributes and isinstance(attributes, tuple):
  673. attributes += (ALL_OPERATIONAL_ATTRIBUTES, ) # concatenate tuple
  674. if isinstance(paged_size, int):
  675. if log_enabled(PROTOCOL):
  676. log(PROTOCOL, 'performing paged search for %d items with cookie <%s> for <%s>', paged_size, escape_bytes(paged_cookie), self)
  677. if controls is None:
  678. controls = []
  679. else:
  680. # Copy the controls to prevent modifying the original object
  681. controls = list(controls)
  682. controls.append(paged_search_control(paged_criticality, paged_size, paged_cookie))
  683. if self.server and self.server.schema and self.check_names:
  684. for attribute_name in attributes:
  685. if ';' in attribute_name: # remove tags
  686. attribute_name_to_check = attribute_name.split(';')[0]
  687. else:
  688. attribute_name_to_check = attribute_name
  689. if self.server.schema and attribute_name_to_check.lower() not in conf_attributes_excluded_from_check and attribute_name_to_check not in self.server.schema.attribute_types:
  690. raise LDAPAttributeError('invalid attribute type ' + attribute_name_to_check)
  691. request = search_operation(search_base,
  692. search_filter,
  693. search_scope,
  694. dereference_aliases,
  695. attributes,
  696. size_limit,
  697. time_limit,
  698. types_only,
  699. self.auto_escape if auto_escape is None else auto_escape,
  700. self.auto_encode,
  701. self.server.schema if self.server else None,
  702. validator=self.server.custom_validator,
  703. check_names=self.check_names)
  704. if log_enabled(PROTOCOL):
  705. log(PROTOCOL, 'SEARCH request <%s> sent via <%s>', search_request_to_dict(request), self)
  706. response = self.post_send_search(self.send('searchRequest', request, controls))
  707. self._entries = []
  708. if isinstance(response, int): # asynchronous strategy
  709. return_value = response
  710. if log_enabled(PROTOCOL):
  711. log(PROTOCOL, 'async SEARCH response id <%s> received via <%s>', return_value, self)
  712. else:
  713. return_value = True if self.result['type'] == 'searchResDone' and len(response) > 0 else False
  714. if not return_value and self.result['result'] not in [RESULT_SUCCESS] and not self.last_error:
  715. self.last_error = self.result['description']
  716. if log_enabled(PROTOCOL):
  717. for entry in response:
  718. if entry['type'] == 'searchResEntry':
  719. log(PROTOCOL, 'SEARCH response entry <%s> received via <%s>', entry, self)
  720. elif entry['type'] == 'searchResRef':
  721. log(PROTOCOL, 'SEARCH response reference <%s> received via <%s>', entry, self)
  722. if log_enabled(BASIC):
  723. log(BASIC, 'done SEARCH operation, result <%s>', return_value)
  724. return return_value
  725. def compare(self,
  726. dn,
  727. attribute,
  728. value,
  729. controls=None):
  730. """
  731. Perform a compare operation
  732. """
  733. conf_attributes_excluded_from_check = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_CHECK')]
  734. if log_enabled(BASIC):
  735. log(BASIC, 'start COMPARE operation via <%s>', self)
  736. self.last_error = None
  737. if self.check_names:
  738. dn = safe_dn(dn)
  739. if log_enabled(EXTENDED):
  740. log(EXTENDED, 'dn sanitized to <%s> for COMPARE operation via <%s>', dn, self)
  741. if self.server and self.server.schema and self.check_names:
  742. if ';' in attribute: # remove tags for checking
  743. attribute_name_to_check = attribute.split(';')[0]
  744. else:
  745. attribute_name_to_check = attribute
  746. if self.server.schema.attribute_types and attribute_name_to_check.lower() not in conf_attributes_excluded_from_check and attribute_name_to_check not in self.server.schema.attribute_types:
  747. raise LDAPAttributeError('invalid attribute type ' + attribute_name_to_check)
  748. if isinstance(value, SEQUENCE_TYPES): # value can't be a sequence
  749. raise LDAPInvalidValueError('value cannot be a sequence')
  750. with self.connection_lock:
  751. self._fire_deferred()
  752. request = compare_operation(dn, attribute, value, self.auto_encode, self.server.schema if self.server else None, validator=self.server.custom_validator if self.server else None, check_names=self.check_names)
  753. if log_enabled(PROTOCOL):
  754. log(PROTOCOL, 'COMPARE request <%s> sent via <%s>', compare_request_to_dict(request), self)
  755. response = self.post_send_single_response(self.send('compareRequest', request, controls))
  756. self._entries = []
  757. if isinstance(response, int):
  758. return_value = response
  759. if log_enabled(PROTOCOL):
  760. log(PROTOCOL, 'async COMPARE response id <%s> received via <%s>', return_value, self)
  761. else:
  762. return_value = True if self.result['type'] == 'compareResponse' and self.result['result'] == RESULT_COMPARE_TRUE else False
  763. if not return_value and self.result['result'] not in [RESULT_COMPARE_TRUE, RESULT_COMPARE_FALSE] and not self.last_error:
  764. self.last_error = self.result['description']
  765. if log_enabled(PROTOCOL):
  766. log(PROTOCOL, 'COMPARE response <%s> received via <%s>', response, self)
  767. if log_enabled(BASIC):
  768. log(BASIC, 'done COMPARE operation, result <%s>', return_value)
  769. return return_value
  770. def add(self,
  771. dn,
  772. object_class=None,
  773. attributes=None,
  774. controls=None):
  775. """
  776. Add dn to the DIT, object_class is None, a class name or a list
  777. of class names.
  778. Attributes is a dictionary in the form 'attr': 'val' or 'attr':
  779. ['val1', 'val2', ...] for multivalued attributes
  780. """
  781. conf_attributes_excluded_from_check = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_CHECK')]
  782. conf_classes_excluded_from_check = [v.lower() for v in get_config_parameter('CLASSES_EXCLUDED_FROM_CHECK')]
  783. if log_enabled(BASIC):
  784. log(BASIC, 'start ADD operation via <%s>', self)
  785. self.last_error = None
  786. _attributes = deepcopy(attributes) # dict could change when adding objectClass values
  787. if self.check_names:
  788. dn = safe_dn(dn)
  789. if log_enabled(EXTENDED):
  790. log(EXTENDED, 'dn sanitized to <%s> for ADD operation via <%s>', dn, self)
  791. with self.connection_lock:
  792. self._fire_deferred()
  793. attr_object_class = []
  794. if object_class is None:
  795. parm_object_class = []
  796. else:
  797. parm_object_class = list(object_class) if isinstance(object_class, SEQUENCE_TYPES) else [object_class]
  798. object_class_attr_name = ''
  799. if _attributes:
  800. for attr in _attributes:
  801. if attr.lower() == 'objectclass':
  802. object_class_attr_name = attr
  803. attr_object_class = list(_attributes[object_class_attr_name]) if isinstance(_attributes[object_class_attr_name], SEQUENCE_TYPES) else [_attributes[object_class_attr_name]]
  804. break
  805. else:
  806. _attributes = dict()
  807. if not object_class_attr_name:
  808. object_class_attr_name = 'objectClass'
  809. attr_object_class = [to_unicode(object_class) for object_class in attr_object_class] # converts objectclass to unicode in case of bytes value
  810. _attributes[object_class_attr_name] = reduce(lambda x, y: x + [y] if y not in x else x, parm_object_class + attr_object_class, []) # remove duplicate ObjectClasses
  811. if not _attributes[object_class_attr_name]:
  812. self.last_error = 'objectClass attribute is mandatory'
  813. if log_enabled(ERROR):
  814. log(ERROR, '%s for <%s>', self.last_error, self)
  815. raise LDAPObjectClassError(self.last_error)
  816. if self.server and self.server.schema and self.check_names:
  817. for object_class_name in _attributes[object_class_attr_name]:
  818. if object_class_name.lower() not in conf_classes_excluded_from_check and object_class_name not in self.server.schema.object_classes:
  819. raise LDAPObjectClassError('invalid object class ' + str(object_class_name))
  820. for attribute_name in _attributes:
  821. if ';' in attribute_name: # remove tags for checking
  822. attribute_name_to_check = attribute_name.split(';')[0]
  823. else:
  824. attribute_name_to_check = attribute_name
  825. if attribute_name_to_check.lower() not in conf_attributes_excluded_from_check and attribute_name_to_check not in self.server.schema.attribute_types:
  826. raise LDAPAttributeError('invalid attribute type ' + attribute_name_to_check)
  827. request = add_operation(dn, _attributes, self.auto_encode, self.server.schema if self.server else None, validator=self.server.custom_validator if self.server else None, check_names=self.check_names)
  828. if log_enabled(PROTOCOL):
  829. log(PROTOCOL, 'ADD request <%s> sent via <%s>', add_request_to_dict(request), self)
  830. response = self.post_send_single_response(self.send('addRequest', request, controls))
  831. self._entries = []
  832. if isinstance(response, STRING_TYPES + (int, )):
  833. return_value = response
  834. if log_enabled(PROTOCOL):
  835. log(PROTOCOL, 'async ADD response id <%s> received via <%s>', return_value, self)
  836. else:
  837. if log_enabled(PROTOCOL):
  838. log(PROTOCOL, 'ADD response <%s> received via <%s>', response, self)
  839. return_value = True if self.result['type'] == 'addResponse' and self.result['result'] == RESULT_SUCCESS else False
  840. if not return_value and self.result['result'] not in [RESULT_SUCCESS] and not self.last_error:
  841. self.last_error = self.result['description']
  842. if log_enabled(BASIC):
  843. log(BASIC, 'done ADD operation, result <%s>', return_value)
  844. return return_value
  845. def delete(self,
  846. dn,
  847. controls=None):
  848. """
  849. Delete the entry identified by the DN from the DIB.
  850. """
  851. if log_enabled(BASIC):
  852. log(BASIC, 'start DELETE operation via <%s>', self)
  853. self.last_error = None
  854. if self.check_names:
  855. dn = safe_dn(dn)
  856. if log_enabled(EXTENDED):
  857. log(EXTENDED, 'dn sanitized to <%s> for DELETE operation via <%s>', dn, self)
  858. with self.connection_lock:
  859. self._fire_deferred()
  860. if self.read_only:
  861. self.last_error = 'connection is read-only'
  862. if log_enabled(ERROR):
  863. log(ERROR, '%s for <%s>', self.last_error, self)
  864. raise LDAPConnectionIsReadOnlyError(self.last_error)
  865. request = delete_operation(dn)
  866. if log_enabled(PROTOCOL):
  867. log(PROTOCOL, 'DELETE request <%s> sent via <%s>', delete_request_to_dict(request), self)
  868. response = self.post_send_single_response(self.send('delRequest', request, controls))
  869. self._entries = []
  870. if isinstance(response, STRING_TYPES + (int, )):
  871. return_value = response
  872. if log_enabled(PROTOCOL):
  873. log(PROTOCOL, 'async DELETE response id <%s> received via <%s>', return_value, self)
  874. else:
  875. if log_enabled(PROTOCOL):
  876. log(PROTOCOL, 'DELETE response <%s> received via <%s>', response, self)
  877. return_value = True if self.result['type'] == 'delResponse' and self.result['result'] == RESULT_SUCCESS else False
  878. if not return_value and self.result['result'] not in [RESULT_SUCCESS] and not self.last_error:
  879. self.last_error = self.result['description']
  880. if log_enabled(BASIC):
  881. log(BASIC, 'done DELETE operation, result <%s>', return_value)
  882. return return_value
  883. def modify(self,
  884. dn,
  885. changes,
  886. controls=None):
  887. """
  888. Modify attributes of entry
  889. - changes is a dictionary in the form {'attribute1': change), 'attribute2': [change, change, ...], ...}
  890. - change is (operation, [value1, value2, ...])
  891. - operation is 0 (MODIFY_ADD), 1 (MODIFY_DELETE), 2 (MODIFY_REPLACE), 3 (MODIFY_INCREMENT)
  892. """
  893. conf_attributes_excluded_from_check = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_CHECK')]
  894. if log_enabled(BASIC):
  895. log(BASIC, 'start MODIFY operation via <%s>', self)
  896. self.last_error = None
  897. if self.check_names:
  898. dn = safe_dn(dn)
  899. if log_enabled(EXTENDED):
  900. log(EXTENDED, 'dn sanitized to <%s> for MODIFY operation via <%s>', dn, self)
  901. with self.connection_lock:
  902. self._fire_deferred()
  903. if self.read_only:
  904. self.last_error = 'connection is read-only'
  905. if log_enabled(ERROR):
  906. log(ERROR, '%s for <%s>', self.last_error, self)
  907. raise LDAPConnectionIsReadOnlyError(self.last_error)
  908. if not isinstance(changes, dict):
  909. self.last_error = 'changes must be a dictionary'
  910. if log_enabled(ERROR):
  911. log(ERROR, '%s for <%s>', self.last_error, self)
  912. raise LDAPChangeError(self.last_error)
  913. if not changes:
  914. self.last_error = 'no changes in modify request'
  915. if log_enabled(ERROR):
  916. log(ERROR, '%s for <%s>', self.last_error, self)
  917. raise LDAPChangeError(self.last_error)
  918. for attribute_name in changes:
  919. if self.server and self.server.schema and self.check_names:
  920. if ';' in attribute_name: # remove tags for checking
  921. attribute_name_to_check = attribute_name.split(';')[0]
  922. else:
  923. attribute_name_to_check = attribute_name
  924. if self.server.schema.attribute_types and attribute_name_to_check.lower() not in conf_attributes_excluded_from_check and attribute_name_to_check not in self.server.schema.attribute_types:
  925. raise LDAPAttributeError('invalid attribute type ' + attribute_name_to_check)
  926. change = changes[attribute_name]
  927. if isinstance(change, SEQUENCE_TYPES) and change[0] in [MODIFY_ADD, MODIFY_DELETE, MODIFY_REPLACE, MODIFY_INCREMENT, 0, 1, 2, 3]:
  928. if len(change) != 2:
  929. self.last_error = 'malformed change'
  930. if log_enabled(ERROR):
  931. log(ERROR, '%s for <%s>', self.last_error, self)
  932. raise LDAPChangeError(self.last_error)
  933. changes[attribute_name] = [change] # insert change in a tuple
  934. else:
  935. for change_operation in change:
  936. if len(change_operation) != 2 or change_operation[0] not in [MODIFY_ADD, MODIFY_DELETE, MODIFY_REPLACE, MODIFY_INCREMENT, 0, 1, 2, 3]:
  937. self.last_error = 'invalid change list'
  938. if log_enabled(ERROR):
  939. log(ERROR, '%s for <%s>', self.last_error, self)
  940. raise LDAPChangeError(self.last_error)
  941. request = modify_operation(dn, changes, self.auto_encode, self.server.schema if self.server else None, validator=self.server.custom_validator if self.server else None, check_names=self.check_names)
  942. if log_enabled(PROTOCOL):
  943. log(PROTOCOL, 'MODIFY request <%s> sent via <%s>', modify_request_to_dict(request), self)
  944. response = self.post_send_single_response(self.send('modifyRequest', request, controls))
  945. self._entries = []
  946. if isinstance(response, STRING_TYPES + (int, )):
  947. return_value = response
  948. if log_enabled(PROTOCOL):
  949. log(PROTOCOL, 'async MODIFY response id <%s> received via <%s>', return_value, self)
  950. else:
  951. if log_enabled(PROTOCOL):
  952. log(PROTOCOL, 'MODIFY response <%s> received via <%s>', response, self)
  953. return_value = True if self.result['type'] == 'modifyResponse' and self.result['result'] == RESULT_SUCCESS else False
  954. if not return_value and self.result['result'] not in [RESULT_SUCCESS] and not self.last_error:
  955. self.last_error = self.result['description']
  956. if log_enabled(BASIC):
  957. log(BASIC, 'done MODIFY operation, result <%s>', return_value)
  958. return return_value
  959. def modify_dn(self,
  960. dn,
  961. relative_dn,
  962. delete_old_dn=True,
  963. new_superior=None,
  964. controls=None):
  965. """
  966. Modify DN of the entry or performs a move of the entry in the
  967. DIT.
  968. """
  969. if log_enabled(BASIC):
  970. log(BASIC, 'start MODIFY DN operation via <%s>', self)
  971. self.last_error = None
  972. if self.check_names:
  973. dn = safe_dn(dn)
  974. if log_enabled(EXTENDED):
  975. log(EXTENDED, 'dn sanitized to <%s> for MODIFY DN operation via <%s>', dn, self)
  976. relative_dn = safe_dn(relative_dn)
  977. if log_enabled(EXTENDED):
  978. log(EXTENDED, 'relative dn sanitized to <%s> for MODIFY DN operation via <%s>', relative_dn, self)
  979. with self.connection_lock:
  980. self._fire_deferred()
  981. if self.read_only:
  982. self.last_error = 'connection is read-only'
  983. if log_enabled(ERROR):
  984. log(ERROR, '%s for <%s>', self.last_error, self)
  985. raise LDAPConnectionIsReadOnlyError(self.last_error)
  986. if new_superior and not dn.startswith(relative_dn): # as per RFC4511 (4.9)
  987. self.last_error = 'DN cannot change while performing moving'
  988. if log_enabled(ERROR):
  989. log(ERROR, '%s for <%s>', self.last_error, self)
  990. raise LDAPChangeError(self.last_error)
  991. request = modify_dn_operation(dn, relative_dn, delete_old_dn, new_superior)
  992. if log_enabled(PROTOCOL):
  993. log(PROTOCOL, 'MODIFY DN request <%s> sent via <%s>', modify_dn_request_to_dict(request), self)
  994. response = self.post_send_single_response(self.send('modDNRequest', request, controls))
  995. self._entries = []
  996. if isinstance(response, STRING_TYPES + (int, )):
  997. return_value = response
  998. if log_enabled(PROTOCOL):
  999. log(PROTOCOL, 'async MODIFY DN response id <%s> received via <%s>', return_value, self)
  1000. else:
  1001. if log_enabled(PROTOCOL):
  1002. log(PROTOCOL, 'MODIFY DN response <%s> received via <%s>', response, self)
  1003. return_value = True if self.result['type'] == 'modDNResponse' and self.result['result'] == RESULT_SUCCESS else False
  1004. if not return_value and self.result['result'] not in [RESULT_SUCCESS] and not self.last_error:
  1005. self.last_error = self.result['description']
  1006. if log_enabled(BASIC):
  1007. log(BASIC, 'done MODIFY DN operation, result <%s>', return_value)
  1008. return return_value
  1009. def abandon(self,
  1010. message_id,
  1011. controls=None):
  1012. """
  1013. Abandon the operation indicated by message_id
  1014. """
  1015. if log_enabled(BASIC):
  1016. log(BASIC, 'start ABANDON operation via <%s>', self)
  1017. self.last_error = None
  1018. with self.connection_lock:
  1019. self._fire_deferred()
  1020. return_value = False
  1021. if self.strategy._outstanding or message_id == 0:
  1022. # only current operation should be abandoned, abandon, bind and unbind cannot ever be abandoned,
  1023. # messagiId 0 is invalid and should be used as a "ping" to keep alive the connection
  1024. if (self.strategy._outstanding and message_id in self.strategy._outstanding and self.strategy._outstanding[message_id]['type'] not in ['abandonRequest', 'bindRequest', 'unbindRequest']) or message_id == 0:
  1025. request = abandon_operation(message_id)
  1026. if log_enabled(PROTOCOL):
  1027. log(PROTOCOL, 'ABANDON request: <%s> sent via <%s>', abandon_request_to_dict(request), self)
  1028. self.send('abandonRequest', request, controls)
  1029. self.result = None
  1030. self.response = None
  1031. self._entries = []
  1032. return_value = True
  1033. else:
  1034. if log_enabled(ERROR):
  1035. log(ERROR, 'cannot abandon a Bind, an Unbind or an Abandon operation or message ID %s not found via <%s>', str(message_id), self)
  1036. if log_enabled(BASIC):
  1037. log(BASIC, 'done ABANDON operation, result <%s>', return_value)
  1038. return return_value
  1039. def extended(self,
  1040. request_name,
  1041. request_value=None,
  1042. controls=None,
  1043. no_encode=None):
  1044. """
  1045. Performs an extended operation
  1046. """
  1047. if log_enabled(BASIC):
  1048. log(BASIC, 'start EXTENDED operation via <%s>', self)
  1049. self.last_error = None
  1050. with self.connection_lock:
  1051. self._fire_deferred()
  1052. request = extended_operation(request_name, request_value, no_encode=no_encode)
  1053. if log_enabled(PROTOCOL):
  1054. log(PROTOCOL, 'EXTENDED request <%s> sent via <%s>', extended_request_to_dict(request), self)
  1055. response = self.post_send_single_response(self.send('extendedReq', request, controls))
  1056. self._entries = []
  1057. if isinstance(response, int):
  1058. return_value = response
  1059. if log_enabled(PROTOCOL):
  1060. log(PROTOCOL, 'async EXTENDED response id <%s> received via <%s>', return_value, self)
  1061. else:
  1062. if log_enabled(PROTOCOL):
  1063. log(PROTOCOL, 'EXTENDED response <%s> received via <%s>', response, self)
  1064. return_value = True if self.result['type'] == 'extendedResp' and self.result['result'] == RESULT_SUCCESS else False
  1065. if not return_value and self.result['result'] not in [RESULT_SUCCESS] and not self.last_error:
  1066. self.last_error = self.result['description']
  1067. if log_enabled(BASIC):
  1068. log(BASIC, 'done EXTENDED operation, result <%s>', return_value)
  1069. return return_value
  1070. def start_tls(self, read_server_info=True): # as per RFC4511. Removal of TLS is defined as MAY in RFC4511 so the client can't implement a generic stop_tls method0
  1071. if log_enabled(BASIC):
  1072. log(BASIC, 'start START TLS operation via <%s>', self)
  1073. with self.connection_lock:
  1074. return_value = False
  1075. if not self.server.tls:
  1076. self.server.tls = Tls()
  1077. if self.lazy and not self._executing_deferred:
  1078. self._deferred_start_tls = True
  1079. self.tls_started = True
  1080. return_value = True
  1081. if log_enabled(BASIC):
  1082. log(BASIC, 'deferring START TLS for <%s>', self)
  1083. else:
  1084. self._deferred_start_tls = False
  1085. if self.server.tls.start_tls(self) and self.strategy.sync: # for asynchronous connections _start_tls is run by the strategy
  1086. if read_server_info:
  1087. self.refresh_server_info() # refresh server info as per RFC4515 (3.1.5)
  1088. return_value = True
  1089. elif not self.strategy.sync:
  1090. return_value = True
  1091. if log_enabled(BASIC):
  1092. log(BASIC, 'done START TLS operation, result <%s>', return_value)
  1093. return return_value
  1094. def do_sasl_bind(self,
  1095. controls):
  1096. if log_enabled(BASIC):
  1097. log(BASIC, 'start SASL BIND operation via <%s>', self)
  1098. self.last_error = None
  1099. with self.connection_lock:
  1100. result = None
  1101. if not self.sasl_in_progress:
  1102. self.sasl_in_progress = True
  1103. try:
  1104. if self.sasl_mechanism == EXTERNAL:
  1105. result = sasl_external(self, controls)
  1106. elif self.sasl_mechanism == DIGEST_MD5:
  1107. result = sasl_digest_md5(self, controls)
  1108. elif self.sasl_mechanism == GSSAPI:
  1109. from ..protocol.sasl.kerberos import sasl_gssapi # needs the gssapi package
  1110. result = sasl_gssapi(self, controls)
  1111. elif self.sasl_mechanism == 'PLAIN':
  1112. result = sasl_plain(self, controls)
  1113. finally:
  1114. self.sasl_in_progress = False
  1115. if log_enabled(BASIC):
  1116. log(BASIC, 'done SASL BIND operation, result <%s>', result)
  1117. return result
  1118. def do_ntlm_bind(self,
  1119. controls):
  1120. if log_enabled(BASIC):
  1121. log(BASIC, 'start NTLM BIND operation via <%s>', self)
  1122. self.last_error = None
  1123. with self.connection_lock:
  1124. result = None
  1125. if not self.sasl_in_progress:
  1126. self.sasl_in_progress = True # ntlm is same of sasl authentication
  1127. # additional import for NTLM
  1128. from ..utils.ntlm import NtlmClient
  1129. domain_name, user_name = self.user.split('\\', 1)
  1130. ntlm_client = NtlmClient(user_name=user_name, domain=domain_name, password=self.password)
  1131. # as per https://msdn.microsoft.com/en-us/library/cc223501.aspx
  1132. # send a sicilyPackageDiscovery request (in the bindRequest)
  1133. request = bind_operation(self.version, 'SICILY_PACKAGE_DISCOVERY', ntlm_client)
  1134. if log_enabled(PROTOCOL):
  1135. log(PROTOCOL, 'NTLM SICILY PACKAGE DISCOVERY request sent via <%s>', self)
  1136. response = self.post_send_single_response(self.send('bindRequest', request, controls))
  1137. if not self.strategy.sync:
  1138. _, result = self.get_response(response)
  1139. else:
  1140. result = response[0]
  1141. if 'server_creds' in result:
  1142. sicily_packages = result['server_creds'].decode('ascii').split(';')
  1143. if 'NTLM' in sicily_packages: # NTLM available on server
  1144. request = bind_operation(self.version, 'SICILY_NEGOTIATE_NTLM', ntlm_client)
  1145. if log_enabled(PROTOCOL):
  1146. log(PROTOCOL, 'NTLM SICILY NEGOTIATE request sent via <%s>', self)
  1147. response = self.post_send_single_response(self.send('bindRequest', request, controls))
  1148. if not self.strategy.sync:
  1149. _, result = self.get_response(response)
  1150. else:
  1151. if log_enabled(PROTOCOL):
  1152. log(PROTOCOL, 'NTLM SICILY NEGOTIATE response <%s> received via <%s>', response[0], self)
  1153. result = response[0]
  1154. if result['result'] == RESULT_SUCCESS:
  1155. request = bind_operation(self.version, 'SICILY_RESPONSE_NTLM', ntlm_client, result['server_creds'])
  1156. if log_enabled(PROTOCOL):
  1157. log(PROTOCOL, 'NTLM SICILY RESPONSE NTLM request sent via <%s>', self)
  1158. response = self.post_send_single_response(self.send('bindRequest', request, controls))
  1159. if not self.strategy.sync:
  1160. _, result = self.get_response(response)
  1161. else:
  1162. if log_enabled(PROTOCOL):
  1163. log(PROTOCOL, 'NTLM BIND response <%s> received via <%s>', response[0], self)
  1164. result = response[0]
  1165. else:
  1166. result = None
  1167. self.sasl_in_progress = False
  1168. if log_enabled(BASIC):
  1169. log(BASIC, 'done SASL NTLM operation, result <%s>', result)
  1170. return result
  1171. def refresh_server_info(self):
  1172. # if self.strategy.no_real_dsa: # do not refresh for mock strategies
  1173. # return
  1174. if not self.strategy.pooled:
  1175. with self.connection_lock:
  1176. if not self.closed:
  1177. if log_enabled(BASIC):
  1178. log(BASIC, 'refreshing server info for <%s>', self)
  1179. previous_response = self.response
  1180. previous_result = self.result
  1181. previous_entries = self._entries
  1182. self.server.get_info_from_server(self)
  1183. self.response = previous_response
  1184. self.result = previous_result
  1185. self._entries = previous_entries
  1186. else:
  1187. if log_enabled(BASIC):
  1188. log(BASIC, 'refreshing server info from pool for <%s>', self)
  1189. self.strategy.pool.get_info_from_server()
  1190. def response_to_ldif(self,
  1191. search_result=None,
  1192. all_base64=False,
  1193. line_separator=None,
  1194. sort_order=None,
  1195. stream=None):
  1196. with self.connection_lock:
  1197. if search_result is None:
  1198. search_result = self.response
  1199. if isinstance(search_result, SEQUENCE_TYPES):
  1200. ldif_lines = operation_to_ldif('searchResponse', search_result, all_base64, sort_order=sort_order)
  1201. ldif_lines = add_ldif_header(ldif_lines)
  1202. line_separator = line_separator or linesep
  1203. ldif_output = line_separator.join(ldif_lines)
  1204. if stream:
  1205. if stream.tell() == 0:
  1206. header = add_ldif_header(['-'])[0]
  1207. stream.write(prepare_for_stream(header + line_separator + line_separator))
  1208. stream.write(prepare_for_stream(ldif_output + line_separator + line_separator))
  1209. if log_enabled(BASIC):
  1210. log(BASIC, 'building LDIF output <%s> for <%s>', ldif_output, self)
  1211. return ldif_output
  1212. return None
  1213. def response_to_json(self,
  1214. raw=False,
  1215. search_result=None,
  1216. indent=4,
  1217. sort=True,
  1218. stream=None,
  1219. checked_attributes=True,
  1220. include_empty=True):
  1221. with self.connection_lock:
  1222. if search_result is None:
  1223. search_result = self.response
  1224. if isinstance(search_result, SEQUENCE_TYPES):
  1225. json_dict = dict()
  1226. json_dict['entries'] = []
  1227. for response in search_result:
  1228. if response['type'] == 'searchResEntry':
  1229. entry = dict()
  1230. entry['dn'] = response['dn']
  1231. if checked_attributes:
  1232. if not include_empty:
  1233. # needed for python 2.6 compatibility
  1234. entry['attributes'] = dict((key, response['attributes'][key]) for key in response['attributes'] if response['attributes'][key])
  1235. else:
  1236. entry['attributes'] = dict(response['attributes'])
  1237. if raw:
  1238. if not include_empty:
  1239. # needed for python 2.6 compatibility
  1240. entry['raw_attributes'] = dict((key, response['raw_attributes'][key]) for key in response['raw_attributes'] if response['raw:attributes'][key])
  1241. else:
  1242. entry['raw'] = dict(response['raw_attributes'])
  1243. json_dict['entries'].append(entry)
  1244. if str is bytes: # Python 2
  1245. check_json_dict(json_dict)
  1246. json_output = json.dumps(json_dict, ensure_ascii=True, sort_keys=sort, indent=indent, check_circular=True, default=format_json, separators=(',', ': '))
  1247. if log_enabled(BASIC):
  1248. log(BASIC, 'building JSON output <%s> for <%s>', json_output, self)
  1249. if stream:
  1250. stream.write(json_output)
  1251. return json_output
  1252. def response_to_file(self,
  1253. target,
  1254. raw=False,
  1255. indent=4,
  1256. sort=True):
  1257. with self.connection_lock:
  1258. if self.response:
  1259. if isinstance(target, STRING_TYPES):
  1260. target = open(target, 'w+')
  1261. if log_enabled(BASIC):
  1262. log(BASIC, 'writing response to file for <%s>', self)
  1263. target.writelines(self.response_to_json(raw=raw, indent=indent, sort=sort))
  1264. target.close()
  1265. def _fire_deferred(self, read_info=True):
  1266. with self.connection_lock:
  1267. if self.lazy and not self._executing_deferred:
  1268. self._executing_deferred = True
  1269. if log_enabled(BASIC):
  1270. log(BASIC, 'executing deferred (open: %s, start_tls: %s, bind: %s) for <%s>', self._deferred_open, self._deferred_start_tls, self._deferred_bind, self)
  1271. try:
  1272. if self._deferred_open:
  1273. self.open(read_server_info=False)
  1274. if self._deferred_start_tls:
  1275. self.start_tls(read_server_info=False)
  1276. if self._deferred_bind:
  1277. self.bind(read_server_info=False, controls=self._bind_controls)
  1278. if read_info:
  1279. self.refresh_server_info()
  1280. except LDAPExceptionError as e:
  1281. if log_enabled(ERROR):
  1282. log(ERROR, '%s for <%s>', e, self)
  1283. raise # re-raise LDAPExceptionError
  1284. finally:
  1285. self._executing_deferred = False
  1286. @property
  1287. def entries(self):
  1288. if self.response:
  1289. if not self._entries:
  1290. self._entries = self._get_entries(self.response)
  1291. return self._entries
  1292. def _get_entries(self, search_response):
  1293. with self.connection_lock:
  1294. from .. import ObjectDef, Reader
  1295. # build a table of ObjectDefs, grouping the entries found in search_response for their attributes set, subset will be included in superset
  1296. attr_sets = []
  1297. for response in search_response:
  1298. if response['type'] == 'searchResEntry':
  1299. resp_attr_set = set(response['attributes'].keys())
  1300. if resp_attr_set not in attr_sets:
  1301. attr_sets.append(resp_attr_set)
  1302. attr_sets.sort(key=lambda x: -len(x)) # sorts the list in descending length order
  1303. unique_attr_sets = []
  1304. for attr_set in attr_sets:
  1305. for unique_set in unique_attr_sets:
  1306. if unique_set >= attr_set: # checks if unique set is a superset of attr_set
  1307. break
  1308. else: # the attr_set is not a subset of any element in unique_attr_sets
  1309. unique_attr_sets.append(attr_set)
  1310. object_defs = []
  1311. for attr_set in unique_attr_sets:
  1312. object_def = ObjectDef(schema=self.server.schema)
  1313. object_def += list(attr_set) # converts the set in a list to be added to the object definition
  1314. object_defs.append((attr_set,
  1315. object_def,
  1316. Reader(self, object_def, self.request['base'], self.request['filter'], attributes=attr_set) if self.strategy.sync else Reader(self, object_def, '', '', attributes=attr_set))
  1317. ) # objects_defs contains a tuple with the set, the ObjectDef and a cursor
  1318. entries = []
  1319. for response in search_response:
  1320. if response['type'] == 'searchResEntry':
  1321. resp_attr_set = set(response['attributes'].keys())
  1322. for object_def in object_defs:
  1323. if resp_attr_set <= object_def[0]: # finds the ObjectDef for the attribute set of this entry
  1324. entry = object_def[2]._create_entry(response)
  1325. entries.append(entry)
  1326. break
  1327. else:
  1328. if log_enabled(ERROR):
  1329. log(ERROR, 'attribute set not found for %s in <%s>', resp_attr_set, self)
  1330. raise LDAPObjectError('attribute set not found for ' + str(resp_attr_set))
  1331. return entries