forked from freeipa/freeipa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipaldap.py
2042 lines (1710 loc) · 72 KB
/
ipaldap.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
# Authors: Rich Megginson <[email protected]>
# Rob Crittenden <[email protected]>
# John Dennis <[email protected]>
#
# Copyright (C) 2007 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import binascii
import errno
import logging
import time
from datetime import datetime
from decimal import Decimal
from copy import deepcopy
import contextlib
import os
import pwd
import warnings
from collections import OrderedDict
from cryptography.hazmat.primitives import serialization
import ldap
import ldap.sasl
import ldap.filter
from ldap.controls import SimplePagedResultsControl, GetEffectiveRightsControl
import ldapurl
import six
# pylint: disable=ipa-forbidden-import
from ipalib import errors, x509, _
from ipalib.constants import LDAP_GENERALIZED_TIME_FORMAT
# pylint: enable=ipa-forbidden-import
from ipaplatform.paths import paths
from ipapython.ipautil import format_netloc, CIDict
from ipapython.dn import DN, RDN
from ipapython.dnsutil import DNSName
from ipapython.kerberos import Principal
from collections.abc import MutableMapping
if six.PY3:
unicode = str
logger = logging.getLogger(__name__)
# Global variable to define SASL auth
SASL_GSSAPI = ldap.sasl.sasl({}, 'GSSAPI')
SASL_GSS_SPNEGO = ldap.sasl.sasl({}, 'GSS-SPNEGO')
_debug_log_ldap = False
_missing = object()
# Autobind modes
AUTOBIND_AUTO = 1
AUTOBIND_ENABLED = 2
AUTOBIND_DISABLED = 3
TRUNCATED_SIZE_LIMIT = object()
TRUNCATED_TIME_LIMIT = object()
TRUNCATED_ADMIN_LIMIT = object()
DIRMAN_DN = DN(('cn', 'directory manager'))
if six.PY2 and hasattr(ldap, 'LDAPBytesWarning'):
# XXX silence python-ldap's BytesWarnings
warnings.filterwarnings(
action="ignore",
category=ldap.LDAPBytesWarning,
)
def realm_to_serverid(realm_name):
"""Convert Kerberos realm name to 389-DS server id"""
return "-".join(realm_name.split("."))
def realm_to_ldapi_uri(realm_name):
"""Get ldapi:// URI to 389-DS's Unix socket"""
serverid = realm_to_serverid(realm_name)
socketname = paths.SLAPD_INSTANCE_SOCKET_TEMPLATE % (serverid,)
return 'ldapi://' + ldapurl.ldapUrlEscape(socketname)
def ldap_initialize(uri, cacertfile=None):
"""Wrapper around ldap.initialize()
The function undoes global and local ldap.conf settings that may cause
issues or reduce security:
* Canonization of SASL host names is disabled.
* With cacertfile=None, the connection uses OpenSSL's default verify
locations, also known as system-wide trust store.
* Cert validation is enforced.
* SSLv2 and SSLv3 are disabled.
"""
conn = ldap.initialize(uri)
# Do not perform reverse DNS lookups to canonicalize SASL host names
conn.set_option(ldap.OPT_X_SASL_NOCANON, ldap.OPT_ON)
if not uri.startswith('ldapi://'):
if cacertfile:
if not os.path.isfile(cacertfile):
raise IOError(errno.ENOENT, cacertfile)
conn.set_option(ldap.OPT_X_TLS_CACERTFILE, cacertfile)
# SSLv3 and SSLv2 are insecure
# OpenLDAP 2.4 sets minimum version with SSL_CTX_set_options(). The
# system-wide crypto-policies for TLS minimum version are applied
# with SSL_CTX_set_min_proto_version(). The set_option() call cannot
# enable lower versions than allowed by crypto-policy, e.g.
# openssl.cnf MinProtocol=TLS1.2 + OPT_X_TLS_PROTOCOL_MIN=TLS1.0
# result in TLS 1.2 as minimum protocol version.
conn.set_option(ldap.OPT_X_TLS_PROTOCOL_MIN, 0x301) # TLS 1.0
# libldap defaults to cert validation, but the default can be
# overridden in global or user local ldap.conf.
conn.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND)
# reinitialize TLS context to materialize settings
conn.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
return conn
class _ServerSchema:
'''
Properties of a schema retrieved from an LDAP server.
'''
def __init__(self, server, schema):
self.server = server
self.schema = schema
self.retrieve_timestamp = time.time()
class SchemaCache:
'''
Cache the schema's from individual LDAP servers.
'''
def __init__(self):
self.servers = {}
def get_schema(self, url, conn, force_update=False):
'''
Return schema belonging to a specific LDAP server.
For performance reasons the schema is retrieved once and
cached unless force_update is True. force_update flushes the
existing schema for the server from the cache and reacquires
it.
'''
if force_update:
self.flush(url)
server_schema = self.servers.get(url)
if server_schema is None:
schema = self._retrieve_schema_from_server(url, conn)
server_schema = _ServerSchema(url, schema)
self.servers[url] = server_schema
return server_schema.schema
def flush(self, url):
logger.debug('flushing %s from SchemaCache', url)
try:
del self.servers[url]
except KeyError:
pass
def _retrieve_schema_from_server(self, url, conn):
"""
Retrieve the LDAP schema from the provided url and determine if
User-Private Groups (upg) are configured.
Bind using kerberos credentials. If in the context of the
in-tree "lite" server then use the current ccache. If in the context of
Apache then create a new ccache and bind using the Apache HTTP service
principal.
If a connection is provided then it the credentials bound to it are
used. The connection is not closed when the request is done.
"""
assert conn is not None
logger.debug(
'retrieving schema for SchemaCache url=%s conn=%s', url, conn)
try:
try:
schema_entry = conn.search_s('cn=schema', ldap.SCOPE_BASE,
attrlist=['attributetypes', 'objectclasses'])[0]
except ldap.NO_SUCH_OBJECT:
# try different location for schema
# openldap has schema located in cn=subschema
logger.debug('cn=schema not found, fallback to cn=subschema')
schema_entry = conn.search_s('cn=subschema', ldap.SCOPE_BASE,
attrlist=['attributetypes', 'objectclasses'])[0]
except ldap.SERVER_DOWN:
raise errors.NetworkError(uri=url,
error=u'LDAP Server Down, unable to retrieve LDAP schema')
except ldap.LDAPError as e:
desc = e.args[0]['desc'].strip()
info = e.args[0].get('info', '').strip()
raise errors.DatabaseError(desc = u'uri=%s' % url,
info = u'Unable to retrieve LDAP schema: %s: %s' % (desc, info))
# no 'cn=schema' entry in LDAP? some servers use 'cn=subschema'
# TODO: DS uses 'cn=schema', support for other server?
# raise a more appropriate exception
return ldap.schema.SubSchema(schema_entry[1])
schema_cache = SchemaCache()
class LDAPEntry(MutableMapping):
__slots__ = ('_conn', '_dn', '_names', '_nice', '_raw', '_sync',
'_not_list', '_orig_raw', '_raw_view',
'_single_value_view')
__hash__ = None
def __init__(self, _conn, _dn=None, _obj=None, **kwargs):
"""
LDAPEntry constructor.
Takes 1 to 3 positional arguments and an arbitrary number of keyword
arguments. The 3 forms of positional arguments are:
* LDAPEntry(entry) - create a shallow copy of an existing LDAPEntry.
* LDAPEntry(dn, entry) - create a shallow copy of an existing
LDAPEntry with a different DN.
* LDAPEntry(conn, dn, mapping) - create a new LDAPEntry using the
specified LDAPClient and DN and optionally initialize
attributes from the specified mapping object.
Keyword arguments can be used to override values of specific attributes.
"""
super(LDAPEntry, self).__init__()
if isinstance(_conn, LDAPEntry):
assert _dn is None
_dn = _conn
_conn = _conn._conn
assert isinstance(_conn, LDAPClient)
if isinstance(_dn, LDAPEntry):
assert _obj is None
_obj = _dn
_dn = _dn._dn
assert isinstance(_dn, DN)
if _obj is None:
_obj = {}
self._conn = _conn
self._dn = _dn
self._names = CIDict()
self._nice = {}
self._raw = {}
self._sync = {}
self._not_list = set()
self._orig_raw = {}
self._raw_view = None
self._single_value_view = None
if isinstance(_obj, LDAPEntry):
self._not_list = set(_obj._not_list)
self._orig_raw = dict(_obj._orig_raw)
if _obj.conn is _conn:
self._names = CIDict(_obj._names)
self._nice = dict(_obj._nice)
self._raw = dict(_obj._raw)
self._sync = dict(_obj._sync)
else:
self.raw.update(_obj.raw)
_obj = {}
self.update(_obj, **kwargs)
@property
def conn(self):
return self._conn
@property
def dn(self):
return self._dn
@dn.setter
def dn(self, value):
assert isinstance(value, DN)
self._dn = value
@property
def raw(self):
if self._raw_view is None:
self._raw_view = RawLDAPEntryView(self)
return self._raw_view
@property
def single_value(self):
if self._single_value_view is None:
self._single_value_view = SingleValueLDAPEntryView(self)
return self._single_value_view
def __repr__(self):
data = dict(self._raw)
data.update((k, v) for k, v in self._nice.items() if v is not None)
return '%s(%r, %r)' % (type(self).__name__, self._dn, data)
def copy(self):
return LDAPEntry(self)
def _sync_attr(self, name):
nice = self._nice[name]
assert isinstance(nice, list)
raw = self._raw[name]
assert isinstance(raw, list)
nice_sync, raw_sync = self._sync.setdefault(name, ([], []))
if nice == nice_sync and raw == raw_sync:
return
nice_adds = set(nice) - set(nice_sync)
nice_dels = set(nice_sync) - set(nice)
raw_adds = set(raw) - set(raw_sync)
raw_dels = set(raw_sync) - set(raw)
for value in nice_dels:
value = self._conn.encode(value)
if value in raw_adds:
continue
raw.remove(value)
for value in raw_dels:
try:
value = self._conn.decode(value, name)
except ValueError as e:
raise ValueError("{error} in LDAP entry '{dn}'".format(
error=e, dn=self._dn))
if value in nice_adds:
continue
nice.remove(value)
for value in sorted(nice_adds, key=nice.index):
value = self._conn.encode(value)
if value in raw_dels:
continue
raw.append(value)
for value in sorted(raw_adds, key=raw.index):
try:
value = self._conn.decode(value, name)
except ValueError as e:
raise ValueError("{error} in LDAP entry '{dn}'".format(
error=e, dn=self._dn))
if value in nice_dels:
continue
nice.append(value)
self._sync[name] = (deepcopy(nice), deepcopy(raw))
if len(nice) > 1:
self._not_list.discard(name)
def _attr_name(self, name):
if not isinstance(name, str):
raise TypeError(
"attribute name must be unicode or str, got %s object %r" % (
name.__class__.__name__, name))
if isinstance(name, bytes):
name = name.decode('utf-8')
return name
def _add_attr_name(self, name):
if name in self._names:
return self._names[name]
if self._conn.schema is not None:
if six.PY2:
encoded_name = name.encode('utf-8')
else:
encoded_name = name
attrtype = self._conn.schema.get_obj(
ldap.schema.AttributeType, encoded_name)
if attrtype is not None:
for altname in attrtype.names:
if six.PY2:
altname = altname.decode('utf-8')
self._names[altname] = name
self._names[name] = name
for oldname in list(self._orig_raw):
if self._names.get(oldname) == name:
self._orig_raw[name] = self._orig_raw.pop(oldname)
break
return name
def _set_nice(self, name, value):
name = self._attr_name(name)
name = self._add_attr_name(name)
if not isinstance(value, list):
if value is None:
value = []
else:
value = [value]
self._not_list.add(name)
else:
self._not_list.discard(name)
if self._nice.get(name) is not value:
self._nice[name] = value
self._raw[name] = None
self._sync.pop(name, None)
if self._raw[name] is not None:
self._sync_attr(name)
def _set_raw(self, name, value):
name = self._attr_name(name)
if not isinstance(value, list):
raise TypeError("%s value must be list, got %s object %r" % (
name, value.__class__.__name__, value))
for (i, item) in enumerate(value):
if not isinstance(item, bytes):
raise TypeError(
"%s[%d] value must be bytes, got %s object %r" % (
name, i, item.__class__.__name__, item)
)
name = self._add_attr_name(name)
if self._raw.get(name) is not value:
self._raw[name] = value
self._nice[name] = None
self._sync.pop(name, None)
if self._nice[name] is not None:
self._sync_attr(name)
def __setitem__(self, name, value):
self._set_nice(name, value)
def _get_attr_name(self, name):
name = self._attr_name(name)
name = self._names[name]
return name
def _get_nice(self, name):
name = self._get_attr_name(name)
value = self._nice[name]
if value is None:
value = self._nice[name] = []
assert isinstance(value, list)
if self._raw[name] is not None:
self._sync_attr(name)
if name in self._not_list:
assert len(value) <= 1
if value:
value = value[0]
else:
value = None
return value
def _get_raw(self, name):
name = self._get_attr_name(name)
value = self._raw[name]
if value is None:
value = self._raw[name] = []
assert isinstance(value, list)
if self._nice[name] is not None:
self._sync_attr(name)
return value
def __getitem__(self, name):
return self._get_nice(name)
def __delitem__(self, name):
name = self._get_attr_name(name)
for (altname, keyname) in list(self._names.items()):
if keyname == name:
del self._names[altname]
del self._nice[name]
del self._raw[name]
self._sync.pop(name, None)
self._not_list.discard(name)
def clear(self):
self._names.clear()
self._nice.clear()
self._raw.clear()
self._sync.clear()
self._not_list.clear()
def __len__(self):
return len(self._nice)
def __contains__(self, name):
return name in self._names
def has_key(self, name):
return name in self
def __eq__(self, other):
if not isinstance(other, LDAPEntry):
return NotImplemented
return other is self
def __ne__(self, other):
if not isinstance(other, LDAPEntry):
return NotImplemented
return other is not self
def reset_modlist(self, other=None):
if other is None:
other = self
assert isinstance(other, LDAPEntry)
self._orig_raw = deepcopy(dict(other.raw))
def generate_modlist(self):
modlist = []
names = set(self)
names.update(self._orig_raw)
for name in names:
new = self.raw.get(name, [])
old = self._orig_raw.get(name, [])
if old and not new:
modlist.append((ldap.MOD_DELETE, name, None))
continue
if not old and new:
modlist.append((ldap.MOD_REPLACE, name, new))
continue
# We used to convert to sets and use difference to calculate
# the changes but this did not preserve order which is important
# particularly for schema
adds = [value for value in new if value not in old]
dels = [value for value in old if value not in new]
if adds and self.conn.get_attribute_single_value(name):
if len(adds) > 1:
raise errors.OnlyOneValueAllowed(attr=name)
modlist.append((ldap.MOD_REPLACE, name, adds))
else:
# dels before adds, in case the same value occurs in
# both due to encoding differences
# (https://pagure.io/freeipa/issue/7750)
if dels:
modlist.append((ldap.MOD_DELETE, name, dels))
if adds:
modlist.append((ldap.MOD_ADD, name, adds))
# Usually the modlist order does not matter.
# However, for schema updates, we want 'attributetypes' before
# 'objectclasses'.
# A simple sort will ensure this.
modlist.sort(key=lambda m: m[1].lower() != 'attributetypes')
return modlist
def __iter__(self):
return iter(self._nice)
class LDAPEntryView(MutableMapping):
__slots__ = ('_entry',)
def __init__(self, entry):
assert isinstance(entry, LDAPEntry)
self._entry = entry
def __delitem__(self, name):
del self._entry[name]
def clear(self):
self._entry.clear()
def __iter__(self):
return iter(self._entry)
def __len__(self):
return len(self._entry)
def __contains__(self, name):
return name in self._entry
def has_key(self, name):
return name in self
class RawLDAPEntryView(LDAPEntryView):
def __getitem__(self, name):
return self._entry._get_raw(name)
def __setitem__(self, name, value):
self._entry._set_raw(name, value)
class SingleValueLDAPEntryView(LDAPEntryView):
def __getitem__(self, name):
value = self._entry[name]
if not isinstance(value, list):
# FIXME: remove when we enforce lists
return value
elif not value:
return None
elif len(value) == 1:
return value[0]
else:
raise ValueError(
'%s has %s values, one expected' % (name, len(value)))
def __setitem__(self, name, value):
if value is None:
self._entry[name] = None
else:
self._entry[name] = [value]
class LDAPClient:
"""LDAP backend class
This class abstracts a LDAP connection, providing methods that work with
LADPEntries.
The purpose of this class is to provide a boundary between IPA and
python-ldap. In IPA we use IPA defined types because they are
richer and are designed to meet our needs. We also require that we
consistently use those types without exception. On the other hand
python-ldap uses different types. The goal is to be able to have
IPA code call python-ldap methods using the types native to
IPA. This class accomplishes that goal by exposing python-ldap
methods which take IPA types, convert them to python-ldap types,
call python-ldap, and then convert the results returned by
python-ldap into IPA types.
"""
# rules for generating filters from entries
MATCH_ANY = '|' # (|(filter1)(filter2))
MATCH_ALL = '&' # (&(filter1)(filter2))
MATCH_NONE = '!' # (!(filter1)(filter2))
# search scope for find_entries()
SCOPE_BASE = ldap.SCOPE_BASE
SCOPE_ONELEVEL = ldap.SCOPE_ONELEVEL
SCOPE_SUBTREE = ldap.SCOPE_SUBTREE
_SYNTAX_MAPPING = {
'1.3.6.1.4.1.1466.115.121.1.1' : bytes, # ACI item
'1.3.6.1.4.1.1466.115.121.1.4' : bytes, # Audio
'1.3.6.1.4.1.1466.115.121.1.5' : bytes, # Binary
'1.3.6.1.4.1.1466.115.121.1.7' : bool, # Boolean
'1.3.6.1.4.1.1466.115.121.1.8' : bytes, # Certificate
'1.3.6.1.4.1.1466.115.121.1.9' : bytes, # Certificate List
'1.3.6.1.4.1.1466.115.121.1.10' : bytes, # Certificate Pair
'1.3.6.1.4.1.1466.115.121.1.12' : DN, # Distinguished Name
'1.3.6.1.4.1.1466.115.121.1.23' : bytes, # Fax
'1.3.6.1.4.1.1466.115.121.1.24' : datetime, # GeneralizedTime
'1.3.6.1.4.1.1466.115.121.1.28' : bytes, # JPEG
'1.3.6.1.4.1.1466.115.121.1.40' : bytes, # OctetString (same as Binary)
'1.3.6.1.4.1.1466.115.121.1.49' : bytes, # Supported Algorithm
'1.3.6.1.4.1.1466.115.121.1.51' : bytes, # Teletext Terminal Identifier
'1.3.6.1.4.1.5322.21.2.5' : datetime, # krbLastAdminUnlock
'2.16.840.1.113730.3.8.3.3' : DN, # enrolledBy
'2.16.840.1.113730.3.8.3.18' : DN, # managedBy
'2.16.840.1.113730.3.8.3.5' : DN, # memberUser
'2.16.840.1.113730.3.8.3.7' : DN, # memberHost
'2.16.840.1.113730.3.8.3.20' : DN, # memberService
'2.16.840.1.113730.3.8.11.4' : DN, # ipaNTFallbackPrimaryGroup
'2.16.840.1.113730.3.8.11.21' : DN, # ipaAllowToImpersonate
'2.16.840.1.113730.3.8.11.22' : DN, # ipaAllowedTarget
'2.16.840.1.113730.3.8.7.1' : DN, # memberAllowCmd
'2.16.840.1.113730.3.8.7.2' : DN, # memberDenyCmd
'2.16.840.1.113719.1.301.4.6.1' : datetime, # krbPrincipalExpiration
'2.16.840.1.113719.1.301.4.14.1' : DN, # krbRealmReferences
'2.16.840.1.113719.1.301.4.17.1' : DN, # krbKdcServers
'2.16.840.1.113719.1.301.4.18.1' : DN, # krbPwdServers
'2.16.840.1.113719.1.301.4.26.1' : DN, # krbPrincipalReferences
'2.16.840.1.113719.1.301.4.29.1' : DN, # krbAdmServers
'2.16.840.1.113719.1.301.4.36.1' : DN, # krbPwdPolicyReference
'2.16.840.1.113719.1.301.4.37.1' : datetime, # krbPasswordExpiration
'2.16.840.1.113719.1.301.4.40.1' : DN, # krbTicketPolicyReference
'2.16.840.1.113719.1.301.4.41.1' : DN, # krbSubTrees
'2.16.840.1.113719.1.301.4.45.1' : datetime, # krbLastPwdChange
'2.16.840.1.113719.1.301.4.48.1' : datetime, # krbLastSuccessfulAuth
'2.16.840.1.113719.1.301.4.49.1' : datetime, # krbLastFailedAuth
'2.16.840.1.113719.1.301.4.52.1' : DN, # krbObjectReferences
'2.16.840.1.113719.1.301.4.53.1' : DN, # krbPrincContainerRef
'2.16.840.1.113730.3.8.16.1.3' : datetime, # ipatokenNotBefore
'2.16.840.1.113730.3.8.16.1.4' : datetime, # ipatokenNotAfter
}
# In most cases we lookup the syntax from the schema returned by
# the server. However, sometimes attributes may not be defined in
# the schema (e.g. extensibleObject which permits undefined
# attributes), or the schema was incorrectly defined (i.e. giving
# an attribute the syntax DirectoryString when in fact it's really
# a DN). This (hopefully sparse) table allows us to trap these
# anomalies and force them to be the syntax we know to be in use.
#
# FWIW, many entries under cn=config are undefined :-(
_SYNTAX_OVERRIDE = CIDict({
'managedtemplate': DN,
'managedbase': DN,
'memberindirect': DN,
'memberofindirect':DN,
'originscope': DN,
'idnsname': DNSName,
'idnssoamname': DNSName,
'idnssoarname': DNSName,
'dnszoneidnsname': DNSName,
'krbcanonicalname': Principal,
'krbprincipalname': Principal,
'usercertificate': x509.IPACertificate,
'usercertificate;binary': x509.IPACertificate,
'cACertificate': x509.IPACertificate,
'cACertificate;binary': x509.IPACertificate,
'nsds5replicalastupdatestart': unicode,
'nsds5replicalastupdateend': unicode,
'nsds5replicalastinitstart': unicode,
'nsds5replicalastinitend': unicode,
})
_SINGLE_VALUE_OVERRIDE = CIDict({
'nsslapd-ssl-check-hostname': True,
'nsslapd-lookthroughlimit': True,
'nsslapd-idlistscanlimit': True,
'nsslapd-anonlimitsdn': True,
'nsslapd-minssf-exclude-rootdse': True,
'nsslapd-enable-upgrade-hash': True,
'nsslapd-db-locks': True,
'nsslapd-logging-hr-timestamps-enabled': True,
'nsslapd-ldapientrysearchbase': True,
'nsslapd-ldapidnmappingbase': True,
'nsslapd-sizelimit': True,
})
time_limit = -1.0 # unlimited
size_limit = 0 # unlimited
def __init__(self, ldap_uri, start_tls=False, force_schema_updates=False,
no_schema=False, decode_attrs=True, cacert=None,
sasl_nocanon=True):
"""Create LDAPClient object.
:param ldap_uri: The LDAP URI to connect to
:param start_tls: Use STARTTLS
:param force_schema_updates:
If true, this object will always request a new schema from the
server. If false, a cached schema will be reused if it exists.
Generally, it should be true if the API context is 'installer' or
'updates', but it must be given explicitly since the API object
is not always available
:param no_schema: If true, schema is never requested from the server.
:param decode_attrs:
If true, attributes are decoded to Python types according to their
syntax.
"""
if ldap_uri is not None:
# special case for ldap2 server plugin
self.ldap_uri = ldap_uri
assert self.protocol in {'ldaps', 'ldapi', 'ldap'}
self._start_tls = start_tls
self._force_schema_updates = force_schema_updates
self._no_schema = no_schema
self._decode_attrs = decode_attrs
self._cacert = cacert
self._sasl_nocanon = sasl_nocanon
self._has_schema = False
self._schema = None
if ldap_uri is not None:
self._conn = self._connect()
@classmethod
def from_realm(cls, realm_name, **kwargs):
"""Create a LDAPI connection to local 389-DS instance
"""
uri = realm_to_ldapi_uri(realm_name)
return cls(uri, start_tls=False, cacert=None, **kwargs)
@classmethod
def from_hostname_secure(cls, hostname, cacert=paths.IPA_CA_CRT,
start_tls=True, **kwargs):
"""Create LDAP or LDAPS connection to a remote 389-DS instance
This constructor is opinionated and doesn't let you shoot yourself in
the foot. It always creates a secure connection. By default it
returns a LDAP connection to port 389 and performs STARTTLS using the
default CA cert. With start_tls=False, it creates a LDAPS connection
to port 636 instead.
Note: Microsoft AD does not support SASL encryption and integrity
verification with a TLS connection. For AD, use a plain connection
with GSSAPI and a MIN_SSF >= 56. SASL GSSAPI and SASL GSS SPNEGO
ensure data integrity and confidentiality with SSF > 1. Also see
https://msdn.microsoft.com/en-us/library/cc223500.aspx
"""
if start_tls:
uri = 'ldap://%s' % format_netloc(hostname, 389)
else:
uri = 'ldaps://%s' % format_netloc(hostname, 636)
return cls(uri, start_tls=start_tls, cacert=cacert, **kwargs)
@classmethod
def from_hostname_plain(cls, hostname, **kwargs):
"""Create a plain LDAP connection with TLS/SSL
Note: A plain TLS connection should only be used in combination with
GSSAPI bind.
"""
assert 'start_tls' not in kwargs
assert 'cacert' not in kwargs
uri = 'ldap://%s' % format_netloc(hostname, 389)
return cls(uri, **kwargs)
def __str__(self):
return self.ldap_uri
def modify_s(self, dn, modlist):
# FIXME: for backwards compatibility only
assert isinstance(dn, DN)
dn = str(dn)
modlist = [(a, b, self.encode(c)) for a, b, c in modlist]
return self.conn.modify_s(dn, modlist)
@property
def conn(self):
return self._conn
@property
def protocol(self):
if self.ldap_uri:
return self.ldap_uri.split('://', 1)[0]
else:
return None
def _get_schema(self):
if self._no_schema:
return None
if not self._has_schema:
try:
schema = schema_cache.get_schema(
self.ldap_uri, self.conn,
force_update=self._force_schema_updates)
except (errors.ExecutionError, IndexError):
schema = None
# bypass ldap2's locking
object.__setattr__(self, '_schema', schema)
object.__setattr__(self, '_has_schema', True)
return self._schema
def _flush_schema(self):
'''
Force this instance to forget it's cached schema and reacquire
it from the schema cache.
'''
# Currently this is called during bind operations to assure
# we're working with valid schema for a specific
# connection. This causes self._get_schema() to query the
# schema cache for the server's schema passing along a flag
# indicating if we're in a context that requires freshly
# loading the schema vs. returning the last cached version of
# the schema. If we're in a mode that permits use of
# previously cached schema the flush and reacquire is a very
# low cost operation.
#
# The schema is reacquired whenever this object is
# instantiated or when binding occurs. The schema is not
# reacquired for operations during a bound connection, it is
# presumed schema cannot change during this interval. This
# provides for maximum efficiency in contexts which do need
# schema refreshing by only peforming the refresh inbetween
# logical operations that have the potential to cause a schema
# change.
# bypass ldap2's locking
object.__setattr__(self, '_has_schema', False)
object.__setattr__(self, '_schema', None)
def get_attribute_type(self, name_or_oid):
if not self._decode_attrs:
return bytes
if six.PY2:
if isinstance(name_or_oid, unicode):
name_or_oid = name_or_oid.encode('utf-8')
# Is this a special case attribute?
if name_or_oid in self._SYNTAX_OVERRIDE:
return self._SYNTAX_OVERRIDE[name_or_oid]
schema = self._get_schema()
if schema is not None:
# Try to lookup the syntax in the schema returned by the server
obj = schema.get_obj(ldap.schema.AttributeType, name_or_oid)
if obj is not None and obj.syntax in self._SYNTAX_MAPPING:
return self._SYNTAX_MAPPING[obj.syntax]
return unicode
def has_dn_syntax(self, name_or_oid):
"""
Check the schema to see if the attribute uses DN syntax.
Returns True/False
"""
return self.get_attribute_type(name_or_oid) is DN
def get_attribute_single_value(self, name_or_oid):
"""
Check the schema to see if the attribute is single-valued.
If the attribute is in the schema then returns True/False
If there is a problem loading the schema or the attribute is
not in the schema return None
"""
if six.PY2 and isinstance(name_or_oid, unicode):
name_or_oid = name_or_oid.encode('utf-8')
if name_or_oid in self._SINGLE_VALUE_OVERRIDE:
return self._SINGLE_VALUE_OVERRIDE[name_or_oid]
schema = self._get_schema()
if schema is not None:
obj = schema.get_obj(ldap.schema.AttributeType, name_or_oid)
if obj is not None:
return obj.single_value
return None
def encode(self, val):
"""
Encode attribute value to LDAP representation (str/bytes).
"""
# Booleans are both an instance of bool and int, therefore
# test for bool before int otherwise the int clause will be
# entered for a boolean value instead of the boolean clause.
if isinstance(val, bool):
if val:
return b'TRUE'
else:
return b'FALSE'
elif isinstance(val, (unicode, int, Decimal, DN, Principal)):
return str(val).encode('utf-8')
elif isinstance(val, DNSName):
return val.to_text().encode('ascii')
elif isinstance(val, bytes):
return val
elif isinstance(val, list):
return [self.encode(m) for m in val]
elif isinstance(val, tuple):
return tuple(self.encode(m) for m in val)
elif isinstance(val, dict):
# key in dict must be str not bytes
dct = dict((k, self.encode(v)) for k, v in val.items())
return dct
elif isinstance(val, datetime):