-
Notifications
You must be signed in to change notification settings - Fork 263
/
connection.py
1627 lines (1455 loc) · 82.1 KB
/
connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
"""
# Created on 2014.05.31
#
# Author: Giovanni Cannata
#
# Copyright 2014 - 2020 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ldap3 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with ldap3 in the COPYING and COPYING.LESSER files.
# If not, see <http://www.gnu.org/licenses/>.
from copy import deepcopy, copy
from os import linesep
from threading import RLock
from functools import reduce
import json
from .. import ANONYMOUS, SIMPLE, SASL, MODIFY_ADD, MODIFY_DELETE, MODIFY_REPLACE, get_config_parameter, DEREF_ALWAYS, \
SUBTREE, ASYNC, SYNC, NO_ATTRIBUTES, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, MODIFY_INCREMENT, LDIF, ASYNC_STREAM, \
RESTARTABLE, ROUND_ROBIN, REUSABLE, AUTO_BIND_DEFAULT, AUTO_BIND_NONE, AUTO_BIND_TLS_BEFORE_BIND, SAFE_SYNC, SAFE_RESTARTABLE, \
AUTO_BIND_TLS_AFTER_BIND, AUTO_BIND_NO_TLS, STRING_TYPES, SEQUENCE_TYPES, MOCK_SYNC, MOCK_ASYNC, NTLM, EXTERNAL,\
DIGEST_MD5, GSSAPI, PLAIN, DSA, SCHEMA, ALL, ENCRYPT, SIGN
from .results import RESULT_SUCCESS, RESULT_COMPARE_TRUE, RESULT_COMPARE_FALSE
from ..extend import ExtendedOperationsRoot
from .pooling import ServerPool
from .server import Server
from ..operation.abandon import abandon_operation, abandon_request_to_dict
from ..operation.add import add_operation, add_request_to_dict
from ..operation.bind import bind_operation, bind_request_to_dict
from ..operation.compare import compare_operation, compare_request_to_dict
from ..operation.delete import delete_operation, delete_request_to_dict
from ..operation.extended import extended_operation, extended_request_to_dict
from ..operation.modify import modify_operation, modify_request_to_dict
from ..operation.modifyDn import modify_dn_operation, modify_dn_request_to_dict
from ..operation.search import search_operation, search_request_to_dict
from ..protocol.rfc2849 import operation_to_ldif, add_ldif_header
from ..protocol.sasl.digestMd5 import sasl_digest_md5
from ..protocol.sasl.external import sasl_external
from ..protocol.sasl.plain import sasl_plain
from ..strategy.sync import SyncStrategy
from ..strategy.safeSync import SafeSyncStrategy
from ..strategy.safeRestartable import SafeRestartableStrategy
from ..strategy.mockAsync import MockAsyncStrategy
from ..strategy.asynchronous import AsyncStrategy
from ..strategy.reusable import ReusableStrategy
from ..strategy.restartable import RestartableStrategy
from ..strategy.ldifProducer import LdifProducerStrategy
from ..strategy.mockSync import MockSyncStrategy
from ..strategy.asyncStream import AsyncStreamStrategy
from ..operation.unbind import unbind_operation
from ..protocol.rfc2696 import paged_search_control
from .usage import ConnectionUsage
from .tls import Tls
from .exceptions import LDAPUnknownStrategyError, LDAPBindError, LDAPUnknownAuthenticationMethodError, \
LDAPSASLMechanismNotSupportedError, LDAPObjectClassError, LDAPConnectionIsReadOnlyError, LDAPChangeError, LDAPExceptionError, \
LDAPObjectError, LDAPSocketReceiveError, LDAPAttributeError, LDAPInvalidValueError, LDAPInvalidPortError, LDAPStartTLSError
from ..utils.conv import escape_bytes, prepare_for_stream, check_json_dict, format_json, to_unicode
from ..utils.log import log, log_enabled, ERROR, BASIC, PROTOCOL, EXTENDED, get_library_log_hide_sensitive_data
from ..utils.dn import safe_dn
from ..utils.port_validators import check_port_and_port_list
SASL_AVAILABLE_MECHANISMS = [EXTERNAL,
DIGEST_MD5,
GSSAPI,
PLAIN]
CLIENT_STRATEGIES = [SYNC,
SAFE_SYNC,
SAFE_RESTARTABLE,
ASYNC,
LDIF,
RESTARTABLE,
REUSABLE,
MOCK_SYNC,
MOCK_ASYNC,
ASYNC_STREAM]
def _format_socket_endpoint(endpoint):
if endpoint and len(endpoint) == 2: # IPv4
return str(endpoint[0]) + ':' + str(endpoint[1])
elif endpoint and len(endpoint) == 4: # IPv6
return '[' + str(endpoint[0]) + ']:' + str(endpoint[1])
try:
return str(endpoint)
except Exception:
return '?'
def _format_socket_endpoints(sock):
if sock:
try:
local = sock.getsockname()
except Exception:
local = (None, None, None, None)
try:
remote = sock.getpeername()
except Exception:
remote = (None, None, None, None)
return '<local: ' + _format_socket_endpoint(local) + ' - remote: ' + _format_socket_endpoint(remote) + '>'
return '<no socket>'
class Connection(object):
"""Main ldap connection class.
Controls, if used, must be a list of tuples. Each tuple must have 3
elements, the control OID, a boolean meaning if the control is
critical, a value.
If the boolean is set to True the server must honor the control or
refuse the operation
Mixing controls must be defined in controls specification (as per
RFC 4511)
:param server: the Server object to connect to
:type server: Server, str
:param user: the user name for simple authentication
:type user: str
:param password: the password for simple authentication
:type password: str
:param session_security: the session security to provide if the authentication protocol supports it
:type session_security: str, can ENCRYPT
:param auto_bind: specify if the bind will be performed automatically when defining the Connection object
:type auto_bind: int, can be one of AUTO_BIND_DEFAULT, AUTO_BIND_NONE, AUTO_BIND_NO_TLS, AUTO_BIND_TLS_BEFORE_BIND, AUTO_BIND_TLS_AFTER_BIND as specified in ldap3
:param version: LDAP version, default to 3
:type version: int
:param authentication: type of authentication
:type authentication: int, can be one of ANONYMOUS, SIMPLE or SASL, as specified in ldap3
:param client_strategy: communication strategy used in the Connection
:type client_strategy: can be one of SYNC, ASYNC, LDIF, RESTARTABLE, REUSABLE as specified in ldap3
:param auto_referrals: specify if the connection object must automatically follow referrals
:type auto_referrals: bool
:param sasl_mechanism: mechanism for SASL authentication, can be one of 'EXTERNAL', 'DIGEST-MD5', 'GSSAPI', 'PLAIN'
:type sasl_mechanism: str
:param sasl_credentials: credentials for SASL mechanism
:type sasl_credentials: tuple
: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
:type check_names: bool
:param collect_usage: collect usage metrics in the usage attribute
:type collect_usage: bool
:param read_only: disable operations that modify data in the LDAP server
:type read_only: bool
:param lazy: open and bind the connection only when an actual operation is performed
:type lazy: bool
:param raise_exceptions: raise exceptions when operations are not successful, if False operations return False if not successful but not raise exceptions
:type raise_exceptions: bool
:param pool_name: pool name for pooled strategies
:type pool_name: str
:param pool_size: pool size for pooled strategies
:type pool_size: int
:param pool_lifetime: pool lifetime for pooled strategies
:type pool_lifetime: int
:param cred_store: credential store for gssapi
:type cred_store: dict
:param use_referral_cache: keep referral connections open and reuse them
:type use_referral_cache: bool
:param auto_escape: automatic escaping of filter values
:type auto_escape: bool
:param auto_encode: automatic encoding of attribute values
:type auto_encode: bool
:param source_address: the ip address or hostname to use as the source when opening the connection to the server
:type source_address: str
:param source_port: the source port to use when opening the connection to the server. Cannot be specified with source_port_list
:type source_port: int
:param source_port_list: a list of source ports to choose from when opening the connection to the server. Cannot be specified with source_port
:type source_port_list: list
"""
def __init__(self,
server,
user=None,
password=None,
session_security=None,
auto_bind=AUTO_BIND_DEFAULT,
version=3,
authentication=None,
client_strategy=SYNC,
auto_referrals=True,
auto_range=True,
sasl_mechanism=None,
sasl_credentials=None,
check_names=True,
collect_usage=False,
read_only=False,
lazy=False,
raise_exceptions=False,
pool_name=None,
pool_size=None,
pool_lifetime=None,
cred_store=None,
fast_decoder=True,
receive_timeout=None,
return_empty_attributes=True,
use_referral_cache=False,
auto_escape=True,
auto_encode=True,
pool_keepalive=None,
source_address=None,
source_port=None,
source_port_list=None):
conf_default_pool_name = get_config_parameter('DEFAULT_THREADED_POOL_NAME')
self.connection_lock = RLock() # re-entrant lock to ensure that operations in the Connection object are executed atomically in the same thread
with self.connection_lock:
if client_strategy not in CLIENT_STRATEGIES:
self.last_error = 'unknown client connection strategy'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPUnknownStrategyError(self.last_error)
self.strategy_type = client_strategy
self.user = user
self.password = password
if not authentication and self.user:
self.authentication = SIMPLE
elif not authentication:
self.authentication = ANONYMOUS
elif authentication in [SIMPLE, ANONYMOUS, SASL, NTLM]:
self.authentication = authentication
else:
self.last_error = 'unknown authentication method'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPUnknownAuthenticationMethodError(self.last_error)
self.version = version
self.auto_referrals = True if auto_referrals else False
self.request = None
self.response = None
self.result = None
self.bound = False
self.listening = False
self.closed = True
self.last_error = None
if auto_bind is False: # compatibility with older version where auto_bind was a boolean
self.auto_bind = AUTO_BIND_DEFAULT
elif auto_bind is True:
self.auto_bind = AUTO_BIND_NO_TLS
else:
self.auto_bind = auto_bind
self.sasl_mechanism = sasl_mechanism
self.sasl_credentials = sasl_credentials
self._usage = ConnectionUsage() if collect_usage else None
self.socket = None
self.tls_started = False
self.sasl_in_progress = False
self.read_only = read_only
self._context_state = []
self._deferred_open = False
self._deferred_bind = False
self._deferred_start_tls = False
self._bind_controls = None
self._executing_deferred = False
self.lazy = lazy
self.pool_name = pool_name if pool_name else conf_default_pool_name
self.pool_size = pool_size
self.cred_store = cred_store
self.pool_lifetime = pool_lifetime
self.pool_keepalive = pool_keepalive
self.starting_tls = False
self.check_names = check_names
self.raise_exceptions = raise_exceptions
self.auto_range = True if auto_range else False
self.extend = ExtendedOperationsRoot(self)
self._entries = []
self.fast_decoder = fast_decoder
self.receive_timeout = receive_timeout
self.empty_attributes = return_empty_attributes
self.use_referral_cache = use_referral_cache
self.auto_escape = auto_escape
self.auto_encode = auto_encode
self._digest_md5_kic = None
self._digest_md5_kis = None
self._digest_md5_kcc_cipher = None
self._digest_md5_kcs_cipher = None
self._digest_md5_sec_num = 0
self.krb_ctx = None
if session_security and not (self.authentication == NTLM or self.sasl_mechanism == GSSAPI):
self.last_error = '"session_security" option only available for NTLM and GSSAPI'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPInvalidValueError(self.last_error)
self.session_security = session_security
port_err = check_port_and_port_list(source_port, source_port_list)
if port_err:
if log_enabled(ERROR):
log(ERROR, port_err)
raise LDAPInvalidPortError(port_err)
# using an empty string to bind a socket means "use the default as if this wasn't provided" because socket
# binding requires that you pass something for the ip if you want to pass a specific port
self.source_address = source_address if source_address is not None else ''
# using 0 as the source port to bind a socket means "use the default behavior of picking a random port from
# all ports as if this wasn't provided" because socket binding requires that you pass something for the port
# if you want to pass a specific ip
self.source_port_list = [0]
if source_port is not None:
self.source_port_list = [source_port]
elif source_port_list is not None:
self.source_port_list = source_port_list[:]
if isinstance(server, STRING_TYPES):
server = Server(server)
if isinstance(server, SEQUENCE_TYPES):
server = ServerPool(server, ROUND_ROBIN, active=True, exhaust=True)
if isinstance(server, ServerPool):
self.server_pool = server
self.server_pool.initialize(self)
self.server = self.server_pool.get_current_server(self)
else:
self.server_pool = None
self.server = server
# if self.authentication == SIMPLE and self.user and self.check_names:
# self.user = safe_dn(self.user)
# if log_enabled(EXTENDED):
# log(EXTENDED, 'user name sanitized to <%s> for simple authentication via <%s>', self.user, self)
if self.strategy_type == SYNC:
self.strategy = SyncStrategy(self)
elif self.strategy_type == SAFE_SYNC:
self.strategy = SafeSyncStrategy(self)
elif self.strategy_type == SAFE_RESTARTABLE:
self.strategy = SafeRestartableStrategy(self)
elif self.strategy_type == ASYNC:
self.strategy = AsyncStrategy(self)
elif self.strategy_type == LDIF:
self.strategy = LdifProducerStrategy(self)
elif self.strategy_type == RESTARTABLE:
self.strategy = RestartableStrategy(self)
elif self.strategy_type == REUSABLE:
self.strategy = ReusableStrategy(self)
self.lazy = False
elif self.strategy_type == MOCK_SYNC:
self.strategy = MockSyncStrategy(self)
elif self.strategy_type == MOCK_ASYNC:
self.strategy = MockAsyncStrategy(self)
elif self.strategy_type == ASYNC_STREAM:
self.strategy = AsyncStreamStrategy(self)
else:
self.last_error = 'unknown strategy'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPUnknownStrategyError(self.last_error)
# maps strategy functions to connection functions
self.send = self.strategy.send
self.open = self.strategy.open
self.get_response = self.strategy.get_response
self.post_send_single_response = self.strategy.post_send_single_response
self.post_send_search = self.strategy.post_send_search
if not self.strategy.no_real_dsa:
self._do_auto_bind()
# else: # for strategies with a fake server set get_info to NONE if server hasn't a schema
# if self.server and not self.server.schema:
# self.server.get_info = NONE
if log_enabled(BASIC):
if get_library_log_hide_sensitive_data():
log(BASIC, 'instantiated Connection: <%s>', self.repr_with_sensitive_data_stripped())
else:
log(BASIC, 'instantiated Connection: <%r>', self)
def _prepare_return_value(self, status, response=False):
if self.strategy.thread_safe:
temp_response = self.response
self.response = None
temp_request = self.request
self.request = None
return status, deepcopy(self.result), deepcopy(temp_response) if response else None, copy(temp_request)
return status
def _do_auto_bind(self):
if self.auto_bind and self.auto_bind not in [AUTO_BIND_NONE, AUTO_BIND_DEFAULT]:
if log_enabled(BASIC):
log(BASIC, 'performing automatic bind for <%s>', self)
if self.closed:
self.open(read_server_info=False)
if self.auto_bind == AUTO_BIND_NO_TLS:
self.bind(read_server_info=True)
elif self.auto_bind == AUTO_BIND_TLS_BEFORE_BIND:
if self.start_tls(read_server_info=False):
self.bind(read_server_info=True)
else:
error = 'automatic start_tls befored bind not successful' + (' - ' + self.last_error if self.last_error else '')
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', error, self)
self.unbind() # unbind anyway to close connection
raise LDAPStartTLSError(error)
elif self.auto_bind == AUTO_BIND_TLS_AFTER_BIND:
self.bind(read_server_info=False)
if not self.start_tls(read_server_info=True):
error = 'automatic start_tls after bind not successful' + (' - ' + self.last_error if self.last_error else '')
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', error, self)
self.unbind()
raise LDAPStartTLSError(error)
if not self.bound:
error = 'automatic bind not successful' + (' - ' + self.last_error if self.last_error else '')
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', error, self)
self.unbind()
raise LDAPBindError(error)
def __str__(self):
s = [
str(self.server) if self.server else 'None',
'user: ' + str(self.user),
'lazy' if self.lazy else 'not lazy',
'unbound' if not self.bound else ('deferred bind' if self._deferred_bind else 'bound'),
'closed' if self.closed else ('deferred open' if self._deferred_open else 'open'),
_format_socket_endpoints(self.socket),
'tls not started' if not self.tls_started else('deferred start_tls' if self._deferred_start_tls else 'tls started'),
'listening' if self.listening else 'not listening',
self.strategy.__class__.__name__ if hasattr(self, 'strategy') else 'No strategy',
'internal decoder' if self.fast_decoder else 'pyasn1 decoder'
]
return ' - '.join(s)
def __repr__(self):
conf_default_pool_name = get_config_parameter('DEFAULT_THREADED_POOL_NAME')
if self.server_pool:
r = 'Connection(server={0.server_pool!r}'.format(self)
else:
r = 'Connection(server={0.server!r}'.format(self)
r += '' if self.user is None else ', user={0.user!r}'.format(self)
r += '' if self.password is None else ', password={0.password!r}'.format(self)
r += '' if self.session_security is None else ',session_security={0.session_security!r}'.format(self)
r += '' if self.auto_bind is None else ', auto_bind={0.auto_bind!r}'.format(self)
r += '' if self.version is None else ', version={0.version!r}'.format(self)
r += '' if self.authentication is None else ', authentication={0.authentication!r}'.format(self)
r += '' if self.strategy_type is None else ', client_strategy={0.strategy_type!r}'.format(self)
r += '' if self.auto_referrals is None else ', auto_referrals={0.auto_referrals!r}'.format(self)
r += '' if self.sasl_mechanism is None else ', sasl_mechanism={0.sasl_mechanism!r}'.format(self)
r += '' if self.sasl_credentials is None else ', sasl_credentials={0.sasl_credentials!r}'.format(self)
r += '' if self.check_names is None else ', check_names={0.check_names!r}'.format(self)
r += '' if self.usage is None else (', collect_usage=' + ('True' if self.usage else 'False'))
r += '' if self.read_only is None else ', read_only={0.read_only!r}'.format(self)
r += '' if self.lazy is None else ', lazy={0.lazy!r}'.format(self)
r += '' if self.raise_exceptions is None else ', raise_exceptions={0.raise_exceptions!r}'.format(self)
r += '' if (self.pool_name is None or self.pool_name == conf_default_pool_name) else ', pool_name={0.pool_name!r}'.format(self)
r += '' if self.pool_size is None else ', pool_size={0.pool_size!r}'.format(self)
r += '' if self.pool_lifetime is None else ', pool_lifetime={0.pool_lifetime!r}'.format(self)
r += '' if self.pool_keepalive is None else ', pool_keepalive={0.pool_keepalive!r}'.format(self)
r += '' if self.cred_store is None else (', cred_store=' + repr(self.cred_store))
r += '' if self.fast_decoder is None else (', fast_decoder=' + ('True' if self.fast_decoder else 'False'))
r += '' if self.auto_range is None else (', auto_range=' + ('True' if self.auto_range else 'False'))
r += '' if self.receive_timeout is None else ', receive_timeout={0.receive_timeout!r}'.format(self)
r += '' if self.empty_attributes is None else (', return_empty_attributes=' + ('True' if self.empty_attributes else 'False'))
r += '' if self.auto_encode is None else (', auto_encode=' + ('True' if self.auto_encode else 'False'))
r += '' if self.auto_escape is None else (', auto_escape=' + ('True' if self.auto_escape else 'False'))
r += '' if self.use_referral_cache is None else (', use_referral_cache=' + ('True' if self.use_referral_cache else 'False'))
r += ')'
return r
def repr_with_sensitive_data_stripped(self):
conf_default_pool_name = get_config_parameter('DEFAULT_THREADED_POOL_NAME')
if self.server_pool:
r = 'Connection(server={0.server_pool!r}'.format(self)
else:
r = 'Connection(server={0.server!r}'.format(self)
r += '' if self.user is None else ', user={0.user!r}'.format(self)
r += '' if self.password is None else ", password='{0}'".format('<stripped %d characters of sensitive data>' % len(self.password))
r += '' if self.session_security is None else ',session_security={0.session_security!r}'.format(self)
r += '' if self.auto_bind is None else ', auto_bind={0.auto_bind!r}'.format(self)
r += '' if self.version is None else ', version={0.version!r}'.format(self)
r += '' if self.authentication is None else ', authentication={0.authentication!r}'.format(self)
r += '' if self.strategy_type is None else ', client_strategy={0.strategy_type!r}'.format(self)
r += '' if self.auto_referrals is None else ', auto_referrals={0.auto_referrals!r}'.format(self)
r += '' if self.sasl_mechanism is None else ', sasl_mechanism={0.sasl_mechanism!r}'.format(self)
if self.sasl_mechanism == DIGEST_MD5:
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])
else:
r += '' if self.sasl_credentials is None else ', sasl_credentials={0.sasl_credentials!r}'.format(self)
r += '' if self.check_names is None else ', check_names={0.check_names!r}'.format(self)
r += '' if self.usage is None else (', collect_usage=' + 'True' if self.usage else 'False')
r += '' if self.read_only is None else ', read_only={0.read_only!r}'.format(self)
r += '' if self.lazy is None else ', lazy={0.lazy!r}'.format(self)
r += '' if self.raise_exceptions is None else ', raise_exceptions={0.raise_exceptions!r}'.format(self)
r += '' if (self.pool_name is None or self.pool_name == conf_default_pool_name) else ', pool_name={0.pool_name!r}'.format(self)
r += '' if self.pool_size is None else ', pool_size={0.pool_size!r}'.format(self)
r += '' if self.pool_lifetime is None else ', pool_lifetime={0.pool_lifetime!r}'.format(self)
r += '' if self.pool_keepalive is None else ', pool_keepalive={0.pool_keepalive!r}'.format(self)
r += '' if self.cred_store is None else (', cred_store=' + repr(self.cred_store))
r += '' if self.fast_decoder is None else (', fast_decoder=' + 'True' if self.fast_decoder else 'False')
r += '' if self.auto_range is None else (', auto_range=' + ('True' if self.auto_range else 'False'))
r += '' if self.receive_timeout is None else ', receive_timeout={0.receive_timeout!r}'.format(self)
r += '' if self.empty_attributes is None else (', return_empty_attributes=' + 'True' if self.empty_attributes else 'False')
r += '' if self.auto_encode is None else (', auto_encode=' + ('True' if self.auto_encode else 'False'))
r += '' if self.auto_escape is None else (', auto_escape=' + ('True' if self.auto_escape else 'False'))
r += '' if self.use_referral_cache is None else (', use_referral_cache=' + ('True' if self.use_referral_cache else 'False'))
r += ')'
return r
@property
def stream(self):
"""Used by the LDIFProducer strategy to accumulate the ldif-change operations with a single LDIF header
:return: reference to the response stream if defined in the strategy.
"""
return self.strategy.get_stream() if self.strategy.can_stream else None
@stream.setter
def stream(self, value):
with self.connection_lock:
if self.strategy.can_stream:
self.strategy.set_stream(value)
@property
def usage(self):
"""Usage statistics for the connection.
:return: Usage object
"""
if not self._usage:
return None
if self.strategy.pooled: # update master connection usage from pooled connections
self._usage.reset()
for worker in self.strategy.pool.workers:
self._usage += worker.connection.usage
self._usage += self.strategy.pool.terminated_usage
return self._usage
def __enter__(self):
with self.connection_lock:
self._context_state.append((self.bound, self.closed)) # save status out of context as a tuple in a list
if self.auto_bind != AUTO_BIND_NONE:
if self.auto_bind == AUTO_BIND_DEFAULT:
self.auto_bind = AUTO_BIND_NO_TLS
if self.closed:
self.open()
if not self.bound:
if not self.bind():
raise LDAPBindError('unable to bind')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
with self.connection_lock:
context_bound, context_closed = self._context_state.pop()
if (not context_bound and self.bound) or self.stream: # restore status prior to entering context
try:
self.unbind()
except LDAPExceptionError:
pass
if not context_closed and self.closed:
self.open()
if exc_type is not None:
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', exc_type, self)
return False # re-raise LDAPExceptionError
def bind(self,
read_server_info=True,
controls=None):
"""Bind to ldap Server with the authentication method and the user defined in the connection
:param read_server_info: reads info from server
:param controls: LDAP controls to send along with the bind operation
:type controls: list of tuple
:return: bool
"""
if log_enabled(BASIC):
log(BASIC, 'start BIND operation via <%s>', self)
self.last_error = None
with self.connection_lock:
if self.lazy and not self._executing_deferred:
if self.strategy.pooled:
self.strategy.validate_bind(controls)
self._deferred_bind = True
self._bind_controls = controls
self.bound = True
if log_enabled(BASIC):
log(BASIC, 'deferring bind for <%s>', self)
else:
self._deferred_bind = False
self._bind_controls = None
if self.closed: # try to open connection if closed
self.open(read_server_info=False)
if self.authentication == ANONYMOUS:
if log_enabled(PROTOCOL):
log(PROTOCOL, 'performing anonymous BIND for <%s>', self)
if not self.strategy.pooled:
request = bind_operation(self.version, self.authentication, self.user, '', auto_encode=self.auto_encode)
if log_enabled(PROTOCOL):
log(PROTOCOL, 'anonymous BIND request <%s> sent via <%s>', bind_request_to_dict(request), self)
response = self.post_send_single_response(self.send('bindRequest', request, controls))
else:
response = self.strategy.validate_bind(controls) # only for REUSABLE
elif self.authentication == SIMPLE:
if log_enabled(PROTOCOL):
log(PROTOCOL, 'performing simple BIND for <%s>', self)
if not self.strategy.pooled:
request = bind_operation(self.version, self.authentication, self.user, self.password, auto_encode=self.auto_encode)
if log_enabled(PROTOCOL):
log(PROTOCOL, 'simple BIND request <%s> sent via <%s>', bind_request_to_dict(request), self)
response = self.post_send_single_response(self.send('bindRequest', request, controls))
else:
response = self.strategy.validate_bind(controls) # only for REUSABLE
elif self.authentication == SASL:
if self.sasl_mechanism in SASL_AVAILABLE_MECHANISMS:
if log_enabled(PROTOCOL):
log(PROTOCOL, 'performing SASL BIND for <%s>', self)
if not self.strategy.pooled:
response = self.do_sasl_bind(controls)
else:
response = self.strategy.validate_bind(controls) # only for REUSABLE
else:
self.last_error = 'requested SASL mechanism not supported'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPSASLMechanismNotSupportedError(self.last_error)
elif self.authentication == NTLM:
if self.user and self.password and len(self.user.split('\\')) == 2:
if log_enabled(PROTOCOL):
log(PROTOCOL, 'performing NTLM BIND for <%s>', self)
if not self.strategy.pooled:
response = self.do_ntlm_bind(controls)
else:
response = self.strategy.validate_bind(controls) # only for REUSABLE
else: # user or password missing
self.last_error = 'NTLM needs domain\\username and a password'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPUnknownAuthenticationMethodError(self.last_error)
else:
self.last_error = 'unknown authentication method'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPUnknownAuthenticationMethodError(self.last_error)
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
_, result = self.get_response(response)
if log_enabled(PROTOCOL):
log(PROTOCOL, 'async BIND response id <%s> received via <%s>', result, self)
elif self.strategy.sync:
result = self.result
if log_enabled(PROTOCOL):
log(PROTOCOL, 'BIND response <%s> received via <%s>', result, self)
elif self.strategy.pooled or self.authentication in (SASL, NTLM): # asynchronous SASL and NTLM or reusable strtegy get the bind result synchronously
result = response
else:
self.last_error = 'unknown authentication method'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPUnknownAuthenticationMethodError(self.last_error)
if result is None:
# self.bound = True if self.strategy_type == REUSABLE else False
self.bound = False
elif result is True:
self.bound = True
elif result is False:
self.bound = False
else:
self.bound = True if result['result'] == RESULT_SUCCESS else False
if not self.bound and result and result['description'] and not self.last_error:
self.last_error = result['description']
if read_server_info and self.bound:
self.refresh_server_info()
self._entries = []
if log_enabled(BASIC):
log(BASIC, 'done BIND operation, result <%s>', self.bound)
return self._prepare_return_value(self.bound, self.result)
def rebind(self,
user=None,
password=None,
authentication=None,
sasl_mechanism=None,
sasl_credentials=None,
read_server_info=True,
controls=None
):
if log_enabled(BASIC):
log(BASIC, 'start (RE)BIND operation via <%s>', self)
self.last_error = None
with self.connection_lock:
if self.session_security == ENCRYPT or self.self.connection._digest_md5_kcs_cipher:
self.last_error = 'Rebind not supported with previous encryption'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPBindError(self.last_error)
if user:
self.user = user
if password is not None:
self.password = password
if not authentication and user:
self.authentication = SIMPLE
if authentication in [SIMPLE, ANONYMOUS, SASL, NTLM]:
self.authentication = authentication
elif authentication is not None:
self.last_error = 'unknown authentication method'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPUnknownAuthenticationMethodError(self.last_error)
if sasl_mechanism:
self.sasl_mechanism = sasl_mechanism
if sasl_credentials:
self.sasl_credentials = sasl_credentials
# if self.authentication == SIMPLE and self.user and self.check_names:
# self.user = safe_dn(self.user)
# if log_enabled(EXTENDED):
# log(EXTENDED, 'user name sanitized to <%s> for rebind via <%s>', self.user, self)
if not self.strategy.pooled:
try:
return self.bind(read_server_info, controls)
except LDAPSocketReceiveError:
self.last_error = 'Unable to rebind as a different user, furthermore the server abruptly closed the connection'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPBindError(self.last_error)
else:
self.strategy.pool.rebind_pool()
return self._prepare_return_value(True, self.result)
def unbind(self,
controls=None):
"""Unbind the connected user. Unbind implies closing session as per RFC4511 (4.3)
:param controls: LDAP controls to send along with the bind operation
"""
if log_enabled(BASIC):
log(BASIC, 'start UNBIND operation via <%s>', self)
if self.use_referral_cache:
self.strategy.unbind_referral_cache()
self.last_error = None
with self.connection_lock:
if self.lazy and not self._executing_deferred and (self._deferred_bind or self._deferred_open): # _clear deferred status
self.strategy.close()
self._deferred_open = False
self._deferred_bind = False
self._deferred_start_tls = False
elif not self.closed:
request = unbind_operation()
if log_enabled(PROTOCOL):
log(PROTOCOL, 'UNBIND request sent via <%s>', self)
self.send('unbindRequest', request, controls)
self.strategy.close()
if log_enabled(BASIC):
log(BASIC, 'done UNBIND operation, result <%s>', True)
return self._prepare_return_value(True)
def search(self,
search_base,
search_filter,
search_scope=SUBTREE,
dereference_aliases=DEREF_ALWAYS,
attributes=None,
size_limit=0,
time_limit=0,
types_only=False,
get_operational_attributes=False,
controls=None,
paged_size=None,
paged_criticality=False,
paged_cookie=None,
auto_escape=None):
"""
Perform an ldap search:
- If attributes is empty noRFC2696 with the specified size
- If paged is 0 and cookie is present the search is abandoned on
server attribute is returned
- If attributes is ALL_ATTRIBUTES all attributes are returned
- If paged_size is an int greater than 0 a simple paged search
is tried as described in
- Cookie is an opaque string received in the last paged search
and must be used on the next paged search response
- If lazy == True open and bind will be deferred until another
LDAP operation is performed
- If mssing_attributes == True then an attribute not returned by the server is set to None
- If auto_escape is set it overrides the Connection auto_escape
"""
conf_attributes_excluded_from_check = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_CHECK')]
if log_enabled(BASIC):
log(BASIC, 'start SEARCH operation via <%s>', self)
if self.check_names and search_base:
search_base = safe_dn(search_base)
if log_enabled(EXTENDED):
log(EXTENDED, 'search base sanitized to <%s> for SEARCH operation via <%s>', search_base, self)
with self.connection_lock:
self._fire_deferred()
if not attributes:
attributes = [NO_ATTRIBUTES]
elif attributes == ALL_ATTRIBUTES:
attributes = [ALL_ATTRIBUTES]
if isinstance(attributes, STRING_TYPES):
attributes = [attributes]
if get_operational_attributes and isinstance(attributes, list):
attributes.append(ALL_OPERATIONAL_ATTRIBUTES)
elif get_operational_attributes and isinstance(attributes, tuple):
attributes += (ALL_OPERATIONAL_ATTRIBUTES, ) # concatenate tuple
if isinstance(paged_size, int):
if log_enabled(PROTOCOL):
log(PROTOCOL, 'performing paged search for %d items with cookie <%s> for <%s>', paged_size, escape_bytes(paged_cookie), self)
if controls is None:
controls = []
else:
# Copy the controls to prevent modifying the original object
controls = list(controls)
controls.append(paged_search_control(paged_criticality, paged_size, paged_cookie))
if self.server and self.server.schema and self.check_names:
for attribute_name in attributes:
if ';' in attribute_name: # remove tags
attribute_name_to_check = attribute_name.split(';')[0]
else:
attribute_name_to_check = attribute_name
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:
self.last_error = 'invalid attribute type ' + attribute_name_to_check
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPAttributeError(self.last_error)
request = search_operation(search_base,
search_filter,
search_scope,
dereference_aliases,
attributes,
size_limit,
time_limit,
types_only,
self.auto_escape if auto_escape is None else auto_escape,
self.auto_encode,
self.server.schema if self.server else None,
validator=self.server.custom_validator,
check_names=self.check_names)
if log_enabled(PROTOCOL):
log(PROTOCOL, 'SEARCH request <%s> sent via <%s>', search_request_to_dict(request), self)
response = self.post_send_search(self.send('searchRequest', request, controls))
self._entries = []
if isinstance(response, int): # asynchronous strategy
return_value = response
if log_enabled(PROTOCOL):
log(PROTOCOL, 'async SEARCH response id <%s> received via <%s>', return_value, self)
else:
return_value = True if self.result['type'] == 'searchResDone' and len(response) > 0 else False
if not return_value and self.result['result'] not in [RESULT_SUCCESS] and not self.last_error:
self.last_error = self.result['description']
if log_enabled(PROTOCOL):
for entry in response:
if entry['type'] == 'searchResEntry':
log(PROTOCOL, 'SEARCH response entry <%s> received via <%s>', entry, self)
elif entry['type'] == 'searchResRef':
log(PROTOCOL, 'SEARCH response reference <%s> received via <%s>', entry, self)
if log_enabled(BASIC):
log(BASIC, 'done SEARCH operation, result <%s>', return_value)
return self._prepare_return_value(return_value, response=True)
def compare(self,
dn,
attribute,
value,
controls=None):
"""
Perform a compare operation
"""
conf_attributes_excluded_from_check = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_CHECK')]
if log_enabled(BASIC):
log(BASIC, 'start COMPARE operation via <%s>', self)
self.last_error = None
if self.check_names:
dn = safe_dn(dn)
if log_enabled(EXTENDED):
log(EXTENDED, 'dn sanitized to <%s> for COMPARE operation via <%s>', dn, self)
if self.server and self.server.schema and self.check_names:
if ';' in attribute: # remove tags for checking
attribute_name_to_check = attribute.split(';')[0]
else:
attribute_name_to_check = attribute
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:
self.last_error = 'invalid attribute type ' + attribute_name_to_check
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPAttributeError(self.last_error)
if isinstance(value, SEQUENCE_TYPES): # value can't be a sequence
self.last_error = 'value cannot be a sequence'
if log_enabled(ERROR):
log(ERROR, '%s for <%s>', self.last_error, self)
raise LDAPInvalidValueError(self.last_error)
with self.connection_lock:
self._fire_deferred()
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)
if log_enabled(PROTOCOL):
log(PROTOCOL, 'COMPARE request <%s> sent via <%s>', compare_request_to_dict(request), self)
response = self.post_send_single_response(self.send('compareRequest', request, controls))
self._entries = []
if isinstance(response, int):
return_value = response
if log_enabled(PROTOCOL):
log(PROTOCOL, 'async COMPARE response id <%s> received via <%s>', return_value, self)
else:
return_value = True if self.result['type'] == 'compareResponse' and self.result['result'] == RESULT_COMPARE_TRUE else False
if not return_value and self.result['result'] not in [RESULT_COMPARE_TRUE, RESULT_COMPARE_FALSE] and not self.last_error:
self.last_error = self.result['description']
if log_enabled(PROTOCOL):
log(PROTOCOL, 'COMPARE response <%s> received via <%s>', response, self)
if log_enabled(BASIC):
log(BASIC, 'done COMPARE operation, result <%s>', return_value)
return self._prepare_return_value(return_value)
def add(self,
dn,
object_class=None,
attributes=None,
controls=None):
"""
Add dn to the DIT, object_class is None, a class name or a list
of class names.
Attributes is a dictionary in the form 'attr': 'val' or 'attr':
['val1', 'val2', ...] for multivalued attributes
"""
conf_attributes_excluded_from_check = [v.lower() for v in get_config_parameter('ATTRIBUTES_EXCLUDED_FROM_CHECK')]
conf_classes_excluded_from_check = [v.lower() for v in get_config_parameter('CLASSES_EXCLUDED_FROM_CHECK')]
if log_enabled(BASIC):
log(BASIC, 'start ADD operation via <%s>', self)
self.last_error = None
_attributes = deepcopy(attributes) # dict could change when adding objectClass values
if self.check_names:
dn = safe_dn(dn)
if log_enabled(EXTENDED):
log(EXTENDED, 'dn sanitized to <%s> for ADD operation via <%s>', dn, self)
with self.connection_lock:
self._fire_deferred()
attr_object_class = []
if object_class is None:
parm_object_class = []
else:
parm_object_class = list(object_class) if isinstance(object_class, SEQUENCE_TYPES) else [object_class]
object_class_attr_name = ''
if _attributes:
for attr in _attributes:
if attr.lower() == 'objectclass':
object_class_attr_name = attr
attr_object_class = list(_attributes[object_class_attr_name]) if isinstance(_attributes[object_class_attr_name], SEQUENCE_TYPES) else [_attributes[object_class_attr_name]]
break
else:
_attributes = dict()
if not object_class_attr_name:
object_class_attr_name = 'objectClass'