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.

base.py 47KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. """
  2. """
  3. # Created on 2013.07.15
  4. #
  5. # Author: Giovanni Cannata
  6. #
  7. # Copyright 2013 - 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 dectails.
  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. import socket
  25. from struct import pack
  26. from platform import system
  27. from sys import exc_info
  28. from time import sleep
  29. from random import choice
  30. from datetime import datetime
  31. from .. import SYNC, ANONYMOUS, get_config_parameter, BASE, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, NO_ATTRIBUTES
  32. from ..core.results import DO_NOT_RAISE_EXCEPTIONS, RESULT_REFERRAL
  33. from ..core.exceptions import LDAPOperationResult, LDAPSASLBindInProgressError, LDAPSocketOpenError, LDAPSessionTerminatedByServerError,\
  34. LDAPUnknownResponseError, LDAPUnknownRequestError, LDAPReferralError, communication_exception_factory, \
  35. LDAPSocketSendError, LDAPExceptionError, LDAPControlError, LDAPResponseTimeoutError, LDAPTransactionError
  36. from ..utils.uri import parse_uri
  37. from ..protocol.rfc4511 import LDAPMessage, ProtocolOp, MessageID, SearchResultEntry
  38. from ..operation.add import add_response_to_dict, add_request_to_dict
  39. from ..operation.modify import modify_request_to_dict, modify_response_to_dict
  40. from ..operation.search import search_result_reference_response_to_dict, search_result_done_response_to_dict,\
  41. search_result_entry_response_to_dict, search_request_to_dict, search_result_entry_response_to_dict_fast,\
  42. search_result_reference_response_to_dict_fast, attributes_to_dict, attributes_to_dict_fast
  43. from ..operation.bind import bind_response_to_dict, bind_request_to_dict, sicily_bind_response_to_dict, bind_response_to_dict_fast, \
  44. sicily_bind_response_to_dict_fast
  45. from ..operation.compare import compare_response_to_dict, compare_request_to_dict
  46. from ..operation.extended import extended_request_to_dict, extended_response_to_dict, intermediate_response_to_dict, extended_response_to_dict_fast, intermediate_response_to_dict_fast
  47. from ..core.server import Server
  48. from ..operation.modifyDn import modify_dn_request_to_dict, modify_dn_response_to_dict
  49. from ..operation.delete import delete_response_to_dict, delete_request_to_dict
  50. from ..protocol.convert import prepare_changes_for_request, build_controls_list
  51. from ..operation.abandon import abandon_request_to_dict
  52. from ..core.tls import Tls
  53. from ..protocol.oid import Oids
  54. from ..protocol.rfc2696 import RealSearchControlValue
  55. from ..protocol.microsoft import DirSyncControlResponseValue
  56. from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, NETWORK, EXTENDED, format_ldap_message
  57. from ..utils.asn1 import encode, decoder, ldap_result_to_dict_fast, decode_sequence
  58. from ..utils.conv import to_unicode
  59. SESSION_TERMINATED_BY_SERVER = 'TERMINATED_BY_SERVER'
  60. TRANSACTION_ERROR = 'TRANSACTION_ERROR'
  61. RESPONSE_COMPLETE = 'RESPONSE_FROM_SERVER_COMPLETE'
  62. # noinspection PyProtectedMember
  63. class BaseStrategy(object):
  64. """
  65. Base class for connection strategy
  66. """
  67. def __init__(self, ldap_connection):
  68. self.connection = ldap_connection
  69. self._outstanding = None
  70. self._referrals = []
  71. self.sync = None # indicates a synchronous connection
  72. self.no_real_dsa = None # indicates a connection to a fake LDAP server
  73. self.pooled = None # Indicates a connection with a connection pool
  74. self.can_stream = None # indicates if a strategy keeps a stream of responses (i.e. LdifProducer can accumulate responses with a single header). Stream must be initialized and closed in _start_listen() and _stop_listen()
  75. self.referral_cache = {}
  76. if log_enabled(BASIC):
  77. log(BASIC, 'instantiated <%s>: <%s>', self.__class__.__name__, self)
  78. def __str__(self):
  79. s = [
  80. str(self.connection) if self.connection else 'None',
  81. 'sync' if self.sync else 'async',
  82. 'no real DSA' if self.no_real_dsa else 'real DSA',
  83. 'pooled' if self.pooled else 'not pooled',
  84. 'can stream output' if self.can_stream else 'cannot stream output',
  85. ]
  86. return ' - '.join(s)
  87. def open(self, reset_usage=True, read_server_info=True):
  88. """
  89. Open a socket to a server. Choose a server from the server pool if available
  90. """
  91. if log_enabled(NETWORK):
  92. log(NETWORK, 'opening connection for <%s>', self.connection)
  93. if self.connection.lazy and not self.connection._executing_deferred:
  94. self.connection._deferred_open = True
  95. self.connection.closed = False
  96. if log_enabled(NETWORK):
  97. log(NETWORK, 'deferring open connection for <%s>', self.connection)
  98. else:
  99. if not self.connection.closed and not self.connection._executing_deferred: # try to close connection if still open
  100. self.close()
  101. self._outstanding = dict()
  102. if self.connection.usage:
  103. if reset_usage or not self.connection._usage.initial_connection_start_time:
  104. self.connection._usage.start()
  105. if self.connection.server_pool:
  106. new_server = self.connection.server_pool.get_server(self.connection) # get a server from the server_pool if available
  107. if self.connection.server != new_server:
  108. self.connection.server = new_server
  109. if self.connection.usage:
  110. self.connection._usage.servers_from_pool += 1
  111. exception_history = []
  112. if not self.no_real_dsa: # tries to connect to a real server
  113. for candidate_address in self.connection.server.candidate_addresses():
  114. try:
  115. if log_enabled(BASIC):
  116. log(BASIC, 'try to open candidate address %s', candidate_address[:-2])
  117. self._open_socket(candidate_address, self.connection.server.ssl, unix_socket=self.connection.server.ipc)
  118. self.connection.server.current_address = candidate_address
  119. self.connection.server.update_availability(candidate_address, True)
  120. break
  121. except Exception:
  122. self.connection.server.update_availability(candidate_address, False)
  123. exception_history.append((datetime.now(), exc_info()[0], exc_info()[1], candidate_address[4]))
  124. if not self.connection.server.current_address and exception_history:
  125. if len(exception_history) == 1: # only one exception, reraise
  126. if log_enabled(ERROR):
  127. log(ERROR, '<%s> for <%s>', exception_history[0][1](exception_history[0][2]), self.connection)
  128. raise exception_history[0][1](exception_history[0][2])
  129. else:
  130. if log_enabled(ERROR):
  131. log(ERROR, 'unable to open socket for <%s>', self.connection)
  132. raise LDAPSocketOpenError('unable to open socket', exception_history)
  133. elif not self.connection.server.current_address:
  134. if log_enabled(ERROR):
  135. log(ERROR, 'invalid server address for <%s>', self.connection)
  136. raise LDAPSocketOpenError('invalid server address')
  137. self.connection._deferred_open = False
  138. self._start_listen()
  139. self.connection.do_auto_bind()
  140. if log_enabled(NETWORK):
  141. log(NETWORK, 'connection open for <%s>', self.connection)
  142. def close(self):
  143. """
  144. Close connection
  145. """
  146. if log_enabled(NETWORK):
  147. log(NETWORK, 'closing connection for <%s>', self.connection)
  148. if self.connection.lazy and not self.connection._executing_deferred and (self.connection._deferred_bind or self.connection._deferred_open):
  149. self.connection.listening = False
  150. self.connection.closed = True
  151. if log_enabled(NETWORK):
  152. log(NETWORK, 'deferred connection closed for <%s>', self.connection)
  153. else:
  154. if not self.connection.closed:
  155. self._stop_listen()
  156. if not self. no_real_dsa:
  157. self._close_socket()
  158. if log_enabled(NETWORK):
  159. log(NETWORK, 'connection closed for <%s>', self.connection)
  160. self.connection.bound = False
  161. self.connection.request = None
  162. self.connection.response = None
  163. self.connection.tls_started = False
  164. self._outstanding = None
  165. self._referrals = []
  166. if not self.connection.strategy.no_real_dsa:
  167. self.connection.server.current_address = None
  168. if self.connection.usage:
  169. self.connection._usage.stop()
  170. def _open_socket(self, address, use_ssl=False, unix_socket=False):
  171. """
  172. Tries to open and connect a socket to a Server
  173. raise LDAPExceptionError if unable to open or connect socket
  174. """
  175. exc = None
  176. try:
  177. self.connection.socket = socket.socket(*address[:3])
  178. except Exception as e:
  179. self.connection.last_error = 'socket creation error: ' + str(e)
  180. exc = e
  181. if exc:
  182. if log_enabled(ERROR):
  183. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  184. raise communication_exception_factory(LDAPSocketOpenError, exc)(self.connection.last_error)
  185. try: # set socket timeout for opening connection
  186. if self.connection.server.connect_timeout:
  187. self.connection.socket.settimeout(self.connection.server.connect_timeout)
  188. self.connection.socket.connect(address[4])
  189. except socket.error as e:
  190. self.connection.last_error = 'socket connection error while opening: ' + str(e)
  191. exc = e
  192. if exc:
  193. if log_enabled(ERROR):
  194. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  195. raise communication_exception_factory(LDAPSocketOpenError, exc)(self.connection.last_error)
  196. # Set connection recv timeout (must be set after connect,
  197. # because socket.settimeout() affects both, connect() as
  198. # well as recv(). Set it before tls.wrap_socket() because
  199. # the recv timeout should take effect during the TLS
  200. # handshake.
  201. if self.connection.receive_timeout is not None:
  202. try: # set receive timeout for the connection socket
  203. self.connection.socket.settimeout(self.connection.receive_timeout)
  204. if system().lower() == 'windows':
  205. self.connection.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, int(1000 * self.connection.receive_timeout))
  206. else:
  207. self.connection.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, pack('LL', self.connection.receive_timeout, 0))
  208. except socket.error as e:
  209. self.connection.last_error = 'unable to set receive timeout for socket connection: ' + str(e)
  210. exc = e
  211. if exc:
  212. if log_enabled(ERROR):
  213. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  214. raise communication_exception_factory(LDAPSocketOpenError, exc)(self.connection.last_error)
  215. if use_ssl:
  216. try:
  217. self.connection.server.tls.wrap_socket(self.connection, do_handshake=True)
  218. if self.connection.usage:
  219. self.connection._usage.wrapped_sockets += 1
  220. except Exception as e:
  221. self.connection.last_error = 'socket ssl wrapping error: ' + str(e)
  222. exc = e
  223. if exc:
  224. if log_enabled(ERROR):
  225. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  226. raise communication_exception_factory(LDAPSocketOpenError, exc)(self.connection.last_error)
  227. if self.connection.usage:
  228. self.connection._usage.open_sockets += 1
  229. self.connection.closed = False
  230. def _close_socket(self):
  231. """
  232. Try to close a socket
  233. don't raise exception if unable to close socket, assume socket is already closed
  234. """
  235. try:
  236. self.connection.socket.shutdown(socket.SHUT_RDWR)
  237. except Exception:
  238. pass
  239. try:
  240. self.connection.socket.close()
  241. except Exception:
  242. pass
  243. self.connection.socket = None
  244. self.connection.closed = True
  245. if self.connection.usage:
  246. self.connection._usage.closed_sockets += 1
  247. def _stop_listen(self):
  248. self.connection.listening = False
  249. def send(self, message_type, request, controls=None):
  250. """
  251. Send an LDAP message
  252. Returns the message_id
  253. """
  254. self.connection.request = None
  255. if self.connection.listening:
  256. if self.connection.sasl_in_progress and message_type not in ['bindRequest']: # as per RFC4511 (4.2.1)
  257. self.connection.last_error = 'cannot send operation requests while SASL bind is in progress'
  258. if log_enabled(ERROR):
  259. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  260. raise LDAPSASLBindInProgressError(self.connection.last_error)
  261. message_id = self.connection.server.next_message_id()
  262. ldap_message = LDAPMessage()
  263. ldap_message['messageID'] = MessageID(message_id)
  264. ldap_message['protocolOp'] = ProtocolOp().setComponentByName(message_type, request)
  265. message_controls = build_controls_list(controls)
  266. if message_controls is not None:
  267. ldap_message['controls'] = message_controls
  268. self.connection.request = BaseStrategy.decode_request(message_type, request, controls)
  269. self._outstanding[message_id] = self.connection.request
  270. self.sending(ldap_message)
  271. else:
  272. self.connection.last_error = 'unable to send message, socket is not open'
  273. if log_enabled(ERROR):
  274. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  275. raise LDAPSocketOpenError(self.connection.last_error)
  276. return message_id
  277. def get_response(self, message_id, timeout=None, get_request=False):
  278. """
  279. Get response LDAP messages
  280. Responses are returned by the underlying connection strategy
  281. Check if message_id LDAP message is still outstanding and wait for timeout to see if it appears in _get_response
  282. Result is stored in connection.result
  283. Responses without result is stored in connection.response
  284. A tuple (responses, result) is returned
  285. """
  286. conf_sleep_interval = get_config_parameter('RESPONSE_SLEEPTIME')
  287. if timeout is None:
  288. timeout = get_config_parameter('RESPONSE_WAITING_TIMEOUT')
  289. response = None
  290. result = None
  291. request = None
  292. if self._outstanding and message_id in self._outstanding:
  293. while timeout >= 0: # waiting for completed message to appear in responses
  294. responses = self._get_response(message_id)
  295. if not responses:
  296. sleep(conf_sleep_interval)
  297. timeout -= conf_sleep_interval
  298. continue
  299. if responses == SESSION_TERMINATED_BY_SERVER:
  300. try: # try to close the session but don't raise any error if server has already closed the session
  301. self.close()
  302. except (socket.error, LDAPExceptionError):
  303. pass
  304. self.connection.last_error = 'session terminated by server'
  305. if log_enabled(ERROR):
  306. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  307. raise LDAPSessionTerminatedByServerError(self.connection.last_error)
  308. elif responses == TRANSACTION_ERROR: # Novell LDAP Transaction unsolicited notification
  309. self.connection.last_error = 'transaction error'
  310. if log_enabled(ERROR):
  311. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  312. raise LDAPTransactionError(self.connection.last_error)
  313. # if referral in response opens a new connection to resolve referrals if requested
  314. if responses[-2]['result'] == RESULT_REFERRAL:
  315. if self.connection.usage:
  316. self.connection._usage.referrals_received += 1
  317. if self.connection.auto_referrals:
  318. ref_response, ref_result = self.do_operation_on_referral(self._outstanding[message_id], responses[-2]['referrals'])
  319. if ref_response is not None:
  320. responses = ref_response + [ref_result]
  321. responses.append(RESPONSE_COMPLETE)
  322. elif ref_result is not None:
  323. responses = [ref_result, RESPONSE_COMPLETE]
  324. self._referrals = []
  325. if responses:
  326. result = responses[-2]
  327. response = responses[:-2]
  328. self.connection.result = None
  329. self.connection.response = None
  330. break
  331. if timeout <= 0:
  332. if log_enabled(ERROR):
  333. log(ERROR, 'socket timeout, no response from server for <%s>', self.connection)
  334. raise LDAPResponseTimeoutError('no response from server')
  335. if self.connection.raise_exceptions and result and result['result'] not in DO_NOT_RAISE_EXCEPTIONS:
  336. if log_enabled(PROTOCOL):
  337. log(PROTOCOL, 'operation result <%s> for <%s>', result, self.connection)
  338. self._outstanding.pop(message_id)
  339. raise LDAPOperationResult(result=result['result'], description=result['description'], dn=result['dn'], message=result['message'], response_type=result['type'])
  340. # checks if any response has a range tag
  341. # self._auto_range_searching is set as a flag to avoid recursive searches
  342. if self.connection.auto_range and not hasattr(self, '_auto_range_searching') and any((True for resp in response if 'raw_attributes' in resp for name in resp['raw_attributes'] if ';range=' in name)):
  343. self._auto_range_searching = result.copy()
  344. temp_response = response[:] # copy
  345. if self.do_search_on_auto_range(self._outstanding[message_id], response):
  346. for resp in temp_response:
  347. if resp['type'] == 'searchResEntry':
  348. keys = [key for key in resp['raw_attributes'] if ';range=' in key]
  349. for key in keys:
  350. del resp['raw_attributes'][key]
  351. del resp['attributes'][key]
  352. response = temp_response
  353. result = self._auto_range_searching
  354. del self._auto_range_searching
  355. if self.connection.empty_attributes:
  356. for entry in response:
  357. if entry['type'] == 'searchResEntry':
  358. for attribute_type in self._outstanding[message_id]['attributes']:
  359. if attribute_type not in entry['raw_attributes'] and attribute_type not in (ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, NO_ATTRIBUTES):
  360. entry['raw_attributes'][attribute_type] = list()
  361. entry['attributes'][attribute_type] = list()
  362. if log_enabled(PROTOCOL):
  363. log(PROTOCOL, 'attribute set to empty list for missing attribute <%s> in <%s>', attribute_type, self)
  364. if not self.connection.auto_range:
  365. attrs_to_remove = []
  366. # removes original empty attribute in case a range tag is returned
  367. for attribute_type in entry['attributes']:
  368. if ';range' in attribute_type.lower():
  369. orig_attr, _, _ = attribute_type.partition(';')
  370. attrs_to_remove.append(orig_attr)
  371. for attribute_type in attrs_to_remove:
  372. if log_enabled(PROTOCOL):
  373. log(PROTOCOL, 'attribute type <%s> removed in response because of same attribute returned as range by the server in <%s>', attribute_type, self)
  374. del entry['raw_attributes'][attribute_type]
  375. del entry['attributes'][attribute_type]
  376. request = self._outstanding.pop(message_id)
  377. else:
  378. if log_enabled(ERROR):
  379. log(ERROR, 'message id not in outstanding queue for <%s>', self.connection)
  380. raise(LDAPResponseTimeoutError('message id not in outstanding queue'))
  381. if get_request:
  382. return response, result, request
  383. else:
  384. return response, result
  385. @staticmethod
  386. def compute_ldap_message_size(data):
  387. """
  388. Compute LDAP Message size according to BER definite length rules
  389. Returns -1 if too few data to compute message length
  390. """
  391. if isinstance(data, str): # fix for Python 2, data is string not bytes
  392. data = bytearray(data) # Python 2 bytearray is equivalent to Python 3 bytes
  393. ret_value = -1
  394. if len(data) > 2:
  395. if data[1] <= 127: # BER definite length - short form. Highest bit of byte 1 is 0, message length is in the last 7 bits - Value can be up to 127 bytes long
  396. ret_value = data[1] + 2
  397. else: # BER definite length - long form. Highest bit of byte 1 is 1, last 7 bits counts the number of following octets containing the value length
  398. bytes_length = data[1] - 128
  399. if len(data) >= bytes_length + 2:
  400. value_length = 0
  401. cont = bytes_length
  402. for byte in data[2:2 + bytes_length]:
  403. cont -= 1
  404. value_length += byte * (256 ** cont)
  405. ret_value = value_length + 2 + bytes_length
  406. return ret_value
  407. def decode_response(self, ldap_message):
  408. """
  409. Convert received LDAPMessage to a dict
  410. """
  411. message_type = ldap_message.getComponentByName('protocolOp').getName()
  412. component = ldap_message['protocolOp'].getComponent()
  413. controls = ldap_message['controls']
  414. if message_type == 'bindResponse':
  415. if not bytes(component['matchedDN']).startswith(b'NTLM'): # patch for microsoft ntlm authentication
  416. result = bind_response_to_dict(component)
  417. else:
  418. result = sicily_bind_response_to_dict(component)
  419. elif message_type == 'searchResEntry':
  420. result = search_result_entry_response_to_dict(component, self.connection.server.schema, self.connection.server.custom_formatter, self.connection.check_names)
  421. elif message_type == 'searchResDone':
  422. result = search_result_done_response_to_dict(component)
  423. elif message_type == 'searchResRef':
  424. result = search_result_reference_response_to_dict(component)
  425. elif message_type == 'modifyResponse':
  426. result = modify_response_to_dict(component)
  427. elif message_type == 'addResponse':
  428. result = add_response_to_dict(component)
  429. elif message_type == 'delResponse':
  430. result = delete_response_to_dict(component)
  431. elif message_type == 'modDNResponse':
  432. result = modify_dn_response_to_dict(component)
  433. elif message_type == 'compareResponse':
  434. result = compare_response_to_dict(component)
  435. elif message_type == 'extendedResp':
  436. result = extended_response_to_dict(component)
  437. elif message_type == 'intermediateResponse':
  438. result = intermediate_response_to_dict(component)
  439. else:
  440. if log_enabled(ERROR):
  441. log(ERROR, 'unknown response <%s> for <%s>', message_type, self.connection)
  442. raise LDAPUnknownResponseError('unknown response')
  443. result['type'] = message_type
  444. if controls:
  445. result['controls'] = dict()
  446. for control in controls:
  447. decoded_control = self.decode_control(control)
  448. result['controls'][decoded_control[0]] = decoded_control[1]
  449. return result
  450. def decode_response_fast(self, ldap_message):
  451. """
  452. Convert received LDAPMessage from fast ber decoder to a dict
  453. """
  454. if ldap_message['protocolOp'] == 1: # bindResponse
  455. if not ldap_message['payload'][1][3].startswith(b'NTLM'): # patch for microsoft ntlm authentication
  456. result = bind_response_to_dict_fast(ldap_message['payload'])
  457. else:
  458. result = sicily_bind_response_to_dict_fast(ldap_message['payload'])
  459. result['type'] = 'bindResponse'
  460. elif ldap_message['protocolOp'] == 4: # searchResEntry'
  461. result = search_result_entry_response_to_dict_fast(ldap_message['payload'], self.connection.server.schema, self.connection.server.custom_formatter, self.connection.check_names)
  462. result['type'] = 'searchResEntry'
  463. elif ldap_message['protocolOp'] == 5: # searchResDone
  464. result = ldap_result_to_dict_fast(ldap_message['payload'])
  465. result['type'] = 'searchResDone'
  466. elif ldap_message['protocolOp'] == 19: # searchResRef
  467. result = search_result_reference_response_to_dict_fast(ldap_message['payload'])
  468. result['type'] = 'searchResRef'
  469. elif ldap_message['protocolOp'] == 7: # modifyResponse
  470. result = ldap_result_to_dict_fast(ldap_message['payload'])
  471. result['type'] = 'modifyResponse'
  472. elif ldap_message['protocolOp'] == 9: # addResponse
  473. result = ldap_result_to_dict_fast(ldap_message['payload'])
  474. result['type'] = 'addResponse'
  475. elif ldap_message['protocolOp'] == 11: # delResponse
  476. result = ldap_result_to_dict_fast(ldap_message['payload'])
  477. result['type'] = 'delResponse'
  478. elif ldap_message['protocolOp'] == 13: # modDNResponse
  479. result = ldap_result_to_dict_fast(ldap_message['payload'])
  480. result['type'] = 'modDNResponse'
  481. elif ldap_message['protocolOp'] == 15: # compareResponse
  482. result = ldap_result_to_dict_fast(ldap_message['payload'])
  483. result['type'] = 'compareResponse'
  484. elif ldap_message['protocolOp'] == 24: # extendedResp
  485. result = extended_response_to_dict_fast(ldap_message['payload'])
  486. result['type'] = 'extendedResp'
  487. elif ldap_message['protocolOp'] == 25: # intermediateResponse
  488. result = intermediate_response_to_dict_fast(ldap_message['payload'])
  489. result['type'] = 'intermediateResponse'
  490. else:
  491. if log_enabled(ERROR):
  492. log(ERROR, 'unknown response <%s> for <%s>', ldap_message['protocolOp'], self.connection)
  493. raise LDAPUnknownResponseError('unknown response')
  494. if ldap_message['controls']:
  495. result['controls'] = dict()
  496. for control in ldap_message['controls']:
  497. decoded_control = self.decode_control_fast(control[3])
  498. result['controls'][decoded_control[0]] = decoded_control[1]
  499. return result
  500. @staticmethod
  501. def decode_control(control):
  502. """
  503. decode control, return a 2-element tuple where the first element is the control oid
  504. and the second element is a dictionary with description (from Oids), criticality and decoded control value
  505. """
  506. control_type = str(control['controlType'])
  507. criticality = bool(control['criticality'])
  508. control_value = bytes(control['controlValue'])
  509. unprocessed = None
  510. if control_type == '1.2.840.113556.1.4.319': # simple paged search as per RFC2696
  511. control_resp, unprocessed = decoder.decode(control_value, asn1Spec=RealSearchControlValue())
  512. control_value = dict()
  513. control_value['size'] = int(control_resp['size'])
  514. control_value['cookie'] = bytes(control_resp['cookie'])
  515. elif control_type == '1.2.840.113556.1.4.841': # DirSync AD
  516. control_resp, unprocessed = decoder.decode(control_value, asn1Spec=DirSyncControlResponseValue())
  517. control_value = dict()
  518. control_value['more_results'] = bool(control_resp['MoreResults']) # more_result if nonzero
  519. control_value['cookie'] = bytes(control_resp['CookieServer'])
  520. elif control_type == '1.3.6.1.1.13.1' or control_type == '1.3.6.1.1.13.2': # Pre-Read control, Post-Read Control as per RFC 4527
  521. control_resp, unprocessed = decoder.decode(control_value, asn1Spec=SearchResultEntry())
  522. control_value = dict()
  523. control_value['result'] = attributes_to_dict(control_resp['attributes'])
  524. if unprocessed:
  525. if log_enabled(ERROR):
  526. log(ERROR, 'unprocessed control response in substrate')
  527. raise LDAPControlError('unprocessed control response in substrate')
  528. return control_type, {'description': Oids.get(control_type, ''), 'criticality': criticality, 'value': control_value}
  529. @staticmethod
  530. def decode_control_fast(control):
  531. """
  532. decode control, return a 2-element tuple where the first element is the control oid
  533. and the second element is a dictionary with description (from Oids), criticality and decoded control value
  534. """
  535. control_type = str(to_unicode(control[0][3], from_server=True))
  536. criticality = False
  537. control_value = None
  538. for r in control[1:]:
  539. if r[2] == 4: # controlValue
  540. control_value = r[3]
  541. else:
  542. criticality = False if r[3] == 0 else True # criticality (booleand default to False)
  543. if control_type == '1.2.840.113556.1.4.319': # simple paged search as per RFC2696
  544. control_resp = decode_sequence(control_value, 0, len(control_value))
  545. control_value = dict()
  546. control_value['size'] = int(control_resp[0][3][0][3])
  547. control_value['cookie'] = bytes(control_resp[0][3][1][3])
  548. elif control_type == '1.2.840.113556.1.4.841': # DirSync AD
  549. control_resp = decode_sequence(control_value, 0, len(control_value))
  550. control_value = dict()
  551. control_value['more_results'] = True if control_resp[0][3][0][3] else False # more_result if nonzero
  552. control_value['cookie'] = control_resp[0][3][2][3]
  553. elif control_type == '1.3.6.1.1.13.1' or control_type == '1.3.6.1.1.13.2': # Pre-Read control, Post-Read Control as per RFC 4527
  554. control_resp = decode_sequence(control_value, 0, len(control_value))
  555. control_value = dict()
  556. control_value['result'] = attributes_to_dict_fast(control_resp[0][3][1][3])
  557. return control_type, {'description': Oids.get(control_type, ''), 'criticality': criticality, 'value': control_value}
  558. @staticmethod
  559. def decode_request(message_type, component, controls=None):
  560. # message_type = ldap_message.getComponentByName('protocolOp').getName()
  561. # component = ldap_message['protocolOp'].getComponent()
  562. if message_type == 'bindRequest':
  563. result = bind_request_to_dict(component)
  564. elif message_type == 'unbindRequest':
  565. result = dict()
  566. elif message_type == 'addRequest':
  567. result = add_request_to_dict(component)
  568. elif message_type == 'compareRequest':
  569. result = compare_request_to_dict(component)
  570. elif message_type == 'delRequest':
  571. result = delete_request_to_dict(component)
  572. elif message_type == 'extendedReq':
  573. result = extended_request_to_dict(component)
  574. elif message_type == 'modifyRequest':
  575. result = modify_request_to_dict(component)
  576. elif message_type == 'modDNRequest':
  577. result = modify_dn_request_to_dict(component)
  578. elif message_type == 'searchRequest':
  579. result = search_request_to_dict(component)
  580. elif message_type == 'abandonRequest':
  581. result = abandon_request_to_dict(component)
  582. else:
  583. if log_enabled(ERROR):
  584. log(ERROR, 'unknown request <%s>', message_type)
  585. raise LDAPUnknownRequestError('unknown request')
  586. result['type'] = message_type
  587. result['controls'] = controls
  588. return result
  589. def valid_referral_list(self, referrals):
  590. referral_list = []
  591. for referral in referrals:
  592. candidate_referral = parse_uri(referral)
  593. if candidate_referral:
  594. for ref_host in self.connection.server.allowed_referral_hosts:
  595. if ref_host[0] == candidate_referral['host'] or ref_host[0] == '*':
  596. if candidate_referral['host'] not in self._referrals:
  597. candidate_referral['anonymousBindOnly'] = not ref_host[1]
  598. referral_list.append(candidate_referral)
  599. break
  600. return referral_list
  601. def do_next_range_search(self, request, response, attr_name):
  602. done = False
  603. current_response = response
  604. while not done:
  605. attr_type, _, returned_range = attr_name.partition(';range=')
  606. _, _, high_range = returned_range.partition('-')
  607. response['raw_attributes'][attr_type] += current_response['raw_attributes'][attr_name]
  608. response['attributes'][attr_type] += current_response['attributes'][attr_name]
  609. if high_range != '*':
  610. if log_enabled(PROTOCOL):
  611. log(PROTOCOL, 'performing next search on auto-range <%s> via <%s>', str(int(high_range) + 1), self.connection)
  612. requested_range = attr_type + ';range=' + str(int(high_range) + 1) + '-*'
  613. result = self.connection.search(search_base=response['dn'],
  614. search_filter='(objectclass=*)',
  615. search_scope=BASE,
  616. dereference_aliases=request['dereferenceAlias'],
  617. attributes=[attr_type + ';range=' + str(int(high_range) + 1) + '-*'])
  618. if isinstance(result, bool):
  619. if result:
  620. current_response = self.connection.response[0]
  621. else:
  622. done = True
  623. else:
  624. current_response, _ = self.get_response(result)
  625. current_response = current_response[0]
  626. if not done:
  627. if requested_range in current_response['raw_attributes'] and len(current_response['raw_attributes'][requested_range]) == 0:
  628. del current_response['raw_attributes'][requested_range]
  629. del current_response['attributes'][requested_range]
  630. attr_name = list(filter(lambda a: ';range=' in a, current_response['raw_attributes'].keys()))[0]
  631. continue
  632. done = True
  633. def do_search_on_auto_range(self, request, response):
  634. for resp in [r for r in response if r['type'] == 'searchResEntry']:
  635. for attr_name in list(resp['raw_attributes'].keys()): # generate list to avoid changing of dict size error
  636. if ';range=' in attr_name:
  637. attr_type, _, range_values = attr_name.partition(';range=')
  638. if range_values in ('1-1', '0-0'): # DirSync returns these values for adding and removing members
  639. return False
  640. if attr_type not in resp['raw_attributes'] or resp['raw_attributes'][attr_type] is None:
  641. resp['raw_attributes'][attr_type] = list()
  642. if attr_type not in resp['attributes'] or resp['attributes'][attr_type] is None:
  643. resp['attributes'][attr_type] = list()
  644. self.do_next_range_search(request, resp, attr_name)
  645. return True
  646. def do_operation_on_referral(self, request, referrals):
  647. if log_enabled(PROTOCOL):
  648. log(PROTOCOL, 'following referral for <%s>', self.connection)
  649. valid_referral_list = self.valid_referral_list(referrals)
  650. if valid_referral_list:
  651. preferred_referral_list = [referral for referral in valid_referral_list if referral['ssl'] == self.connection.server.ssl]
  652. selected_referral = choice(preferred_referral_list) if preferred_referral_list else choice(valid_referral_list)
  653. cachekey = (selected_referral['host'], selected_referral['port'] or self.connection.server.port, selected_referral['ssl'])
  654. if self.connection.use_referral_cache and cachekey in self.referral_cache:
  655. referral_connection = self.referral_cache[cachekey]
  656. else:
  657. referral_server = Server(host=selected_referral['host'],
  658. port=selected_referral['port'] or self.connection.server.port,
  659. use_ssl=selected_referral['ssl'],
  660. get_info=self.connection.server.get_info,
  661. formatter=self.connection.server.custom_formatter,
  662. connect_timeout=self.connection.server.connect_timeout,
  663. mode=self.connection.server.mode,
  664. allowed_referral_hosts=self.connection.server.allowed_referral_hosts,
  665. tls=Tls(local_private_key_file=self.connection.server.tls.private_key_file,
  666. local_certificate_file=self.connection.server.tls.certificate_file,
  667. validate=self.connection.server.tls.validate,
  668. version=self.connection.server.tls.version,
  669. ca_certs_file=self.connection.server.tls.ca_certs_file) if selected_referral['ssl'] else None)
  670. from ..core.connection import Connection
  671. referral_connection = Connection(server=referral_server,
  672. user=self.connection.user if not selected_referral['anonymousBindOnly'] else None,
  673. password=self.connection.password if not selected_referral['anonymousBindOnly'] else None,
  674. version=self.connection.version,
  675. authentication=self.connection.authentication if not selected_referral['anonymousBindOnly'] else ANONYMOUS,
  676. client_strategy=SYNC,
  677. auto_referrals=True,
  678. read_only=self.connection.read_only,
  679. check_names=self.connection.check_names,
  680. raise_exceptions=self.connection.raise_exceptions,
  681. fast_decoder=self.connection.fast_decoder,
  682. receive_timeout=self.connection.receive_timeout,
  683. sasl_mechanism=self.connection.sasl_mechanism,
  684. sasl_credentials=self.connection.sasl_credentials)
  685. if self.connection.usage:
  686. self.connection._usage.referrals_connections += 1
  687. referral_connection.open()
  688. referral_connection.strategy._referrals = self._referrals
  689. if self.connection.tls_started and not referral_server.ssl: # if the original server was in start_tls mode and the referral server is not in ssl then start_tls on the referral connection
  690. referral_connection.start_tls()
  691. if self.connection.bound:
  692. referral_connection.bind()
  693. if self.connection.usage:
  694. self.connection._usage.referrals_followed += 1
  695. if request['type'] == 'searchRequest':
  696. referral_connection.search(selected_referral['base'] or request['base'],
  697. selected_referral['filter'] or request['filter'],
  698. selected_referral['scope'] or request['scope'],
  699. request['dereferenceAlias'],
  700. selected_referral['attributes'] or request['attributes'],
  701. request['sizeLimit'],
  702. request['timeLimit'],
  703. request['typesOnly'],
  704. controls=request['controls'])
  705. elif request['type'] == 'addRequest':
  706. referral_connection.add(selected_referral['base'] or request['entry'],
  707. None,
  708. request['attributes'],
  709. controls=request['controls'])
  710. elif request['type'] == 'compareRequest':
  711. referral_connection.compare(selected_referral['base'] or request['entry'],
  712. request['attribute'],
  713. request['value'],
  714. controls=request['controls'])
  715. elif request['type'] == 'delRequest':
  716. referral_connection.delete(selected_referral['base'] or request['entry'],
  717. controls=request['controls'])
  718. elif request['type'] == 'extendedReq':
  719. referral_connection.extended(request['name'],
  720. request['value'],
  721. controls=request['controls'],
  722. no_encode=True
  723. )
  724. elif request['type'] == 'modifyRequest':
  725. referral_connection.modify(selected_referral['base'] or request['entry'],
  726. prepare_changes_for_request(request['changes']),
  727. controls=request['controls'])
  728. elif request['type'] == 'modDNRequest':
  729. referral_connection.modify_dn(selected_referral['base'] or request['entry'],
  730. request['newRdn'],
  731. request['deleteOldRdn'],
  732. request['newSuperior'],
  733. controls=request['controls'])
  734. else:
  735. self.connection.last_error = 'referral operation not permitted'
  736. if log_enabled(ERROR):
  737. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  738. raise LDAPReferralError(self.connection.last_error)
  739. response = referral_connection.response
  740. result = referral_connection.result
  741. if self.connection.use_referral_cache:
  742. self.referral_cache[cachekey] = referral_connection
  743. else:
  744. referral_connection.unbind()
  745. else:
  746. response = None
  747. result = None
  748. return response, result
  749. def sending(self, ldap_message):
  750. exc = None
  751. if log_enabled(NETWORK):
  752. log(NETWORK, 'sending 1 ldap message for <%s>', self.connection)
  753. try:
  754. encoded_message = encode(ldap_message)
  755. self.connection.socket.sendall(encoded_message)
  756. if log_enabled(EXTENDED):
  757. log(EXTENDED, 'ldap message sent via <%s>:%s', self.connection, format_ldap_message(ldap_message, '>>'))
  758. if log_enabled(NETWORK):
  759. log(NETWORK, 'sent %d bytes via <%s>', len(encoded_message), self.connection)
  760. except socket.error as e:
  761. self.connection.last_error = 'socket sending error' + str(e)
  762. exc = e
  763. encoded_message = None
  764. if exc:
  765. if log_enabled(ERROR):
  766. log(ERROR, '<%s> for <%s>', self.connection.last_error, self.connection)
  767. raise communication_exception_factory(LDAPSocketSendError, exc)(self.connection.last_error)
  768. if self.connection.usage:
  769. self.connection._usage.update_transmitted_message(self.connection.request, len(encoded_message))
  770. def _start_listen(self):
  771. # overridden on strategy class
  772. raise NotImplementedError
  773. def _get_response(self, message_id):
  774. # overridden in strategy class
  775. raise NotImplementedError
  776. def receiving(self):
  777. # overridden in strategy class
  778. raise NotImplementedError
  779. def post_send_single_response(self, message_id):
  780. # overridden in strategy class
  781. raise NotImplementedError
  782. def post_send_search(self, message_id):
  783. # overridden in strategy class
  784. raise NotImplementedError
  785. def get_stream(self):
  786. raise NotImplementedError
  787. def set_stream(self, value):
  788. raise NotImplementedError
  789. def unbind_referral_cache(self):
  790. while len(self.referral_cache) > 0:
  791. cachekey, referral_connection = self.referral_cache.popitem()
  792. referral_connection.unbind()