-
Notifications
You must be signed in to change notification settings - Fork 478
/
freenasldap.py
executable file
·3461 lines (2750 loc) · 101 KB
/
freenasldap.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
# Copyright 2010 iXsystems, Inc.
# All rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
#####################################################################
import asyncore
import grp
import ldap
import ldap.sasl
import logging
import os
import pwd
import socket
import tempfile
import time
import ipaddr
from dns import resolver
from ldap.controls import SimplePagedResultsControl
from .log import log_traceback
from freenasUI.common.pipesubr import (
pipeopen,
run
)
from freenasUI.common.freenassysctl import freenas_sysctl as _fs
from freenasUI.common.system import (
get_freenas_var,
get_freenas_var_by_file,
ldap_objects,
activedirectory_objects,
get_hostname
)
from freenasUI.common.freenascache import (
FreeNAS_UserCache,
FreeNAS_GroupCache,
FreeNAS_LDAP_QueryCache,
FreeNAS_Directory_UserCache,
FreeNAS_Directory_GroupCache,
FLAGS_CACHE_READ_USER,
FLAGS_CACHE_READ_GROUP,
FLAGS_CACHE_WRITE_USER,
FLAGS_CACHE_WRITE_GROUP
)
from freenasUI.middleware.client import client
log = logging.getLogger('common.freenasldap')
FREENAS_LDAP_NOSSL = " off"
FREENAS_LDAP_USESSL = "on"
FREENAS_LDAP_USETLS = "start_tls"
FREENAS_LDAP_PORT = get_freenas_var("FREENAS_LDAP_PORT", 389)
FREENAS_LDAP_SSL_PORT = get_freenas_var("FREENAS_LDAP_SSL_PORT", 636)
FREENAS_AD_SEPARATOR = get_freenas_var("FREENAS_AD_SEPARATOR", '\\')
FREENAS_AD_CONFIG_FILE = get_freenas_var(
"AD_CONFIG_FILE",
"/etc/directoryservice/ActiveDirectory/config"
)
FREENAS_LDAP_CACHE_EXPIRE = get_freenas_var("FREENAS_LDAP_CACHE_EXPIRE", 60)
FREENAS_LDAP_CACHE_ENABLE = get_freenas_var("FREENAS_LDAP_CACHE_ENABLE", 1)
FREENAS_LDAP_VERSION = ldap.VERSION3
FREENAS_LDAP_REFERRALS = get_freenas_var("FREENAS_LDAP_REFERRALS", 0)
FREENAS_LDAP_PAGESIZE = get_freenas_var("FREENAS_LDAP_PAGESIZE", 1024)
DS_DEBUG = False
ldap.protocol_version = FREENAS_LDAP_VERSION
ldap.set_option(ldap.OPT_REFERRALS, FREENAS_LDAP_REFERRALS)
FLAGS_DBINIT = 0x00010000
FLAGS_AD_ENABLED = 0x00100000
FLAGS_LDAP_ENABLED = 0x00200000
FLAGS_PREFER_IPv6 = 0x00400000
FLAGS_SASL_GSSAPI = 0x00800000
class FreeNAS_LDAP_Directory_Exception(Exception):
pass
class FreeNAS_ActiveDirectory_Exception(FreeNAS_LDAP_Directory_Exception):
pass
class FreeNAS_LDAP_Exception(FreeNAS_LDAP_Directory_Exception):
pass
class FreeNAS_LDAP_Directory(object):
@staticmethod
def validate_credentials(
hostname, port=389, basedn=None, binddn=None, bindpw=None, ssl='off',
certfile=None, errors=[]
):
FreeNAS_LDAP(
host=hostname,
port=port,
binddn=binddn,
bindpw=bindpw,
basedn=basedn,
certfile=certfile,
ssl=ssl
).open()
def __init__(self, **kwargs):
self.host = kwargs.get('host', None)
self.port = None
if 'port' in kwargs and kwargs['port'] is not None:
self.port = int(kwargs['port'])
self.binddn = kwargs.get('binddn', None)
self.bindpw = kwargs.get('bindpw', None)
self.basedn = kwargs.get('basedn', None)
self.anonbind = kwargs.get('anonbind', False)
self.ssl = FREENAS_LDAP_NOSSL
if 'ssl' in kwargs and kwargs['ssl'] is not None:
self.ssl = kwargs['ssl']
if self.ssl == FREENAS_LDAP_USESSL and self.port is None:
self.port = FREENAS_LDAP_SSL_PORT
self.certfile = kwargs.get('certfile', None)
if self.port is None:
self.port = FREENAS_LDAP_PORT
self.scope = ldap.SCOPE_SUBTREE
if 'scope' in kwargs and kwargs['scope'] is not None:
self.scope = kwargs['scope']
self.filter = kwargs.get('filter', None)
self.attributes = kwargs.get('attributes', None)
self.pagesize = 0
if 'pagesize' in kwargs and kwargs['pagesize'] is not None:
self.pagesize = kwargs['pagesize']
self.flags = 0
if 'flags' in kwargs and kwargs['flags'] is not None:
self.flags = kwargs['flags']
self._handle = None
self._isopen = False
self._cache = FreeNAS_LDAP_QueryCache()
self._settings = []
if DS_DEBUG:
log.debug(
"FreeNAS_LDAP_Directory.__init__: "
"host = %s, port = %ld, binddn = %s, basedn = %s, ssl = %s",
self.host, self.port, self.binddn, self.basedn, self.ssl
)
def _save(self):
_s = {}
_s.update(self.__dict__)
self._settings.append(_s)
def _restore(self):
if self._settings:
_s = self._settings.pop()
self.__dict__.update(_s)
def _logex(self, ex):
log.debug("FreeNAS_LDAP_Directory[ERROR]: An LDAP Exception occured", exc_info=True)
if not hasattr(ex, '__iter__'):
log.debug('FreeNAS_LDAP_Directory[ERROR]: %s', ex, exc_info=True)
return
for e in ex:
if 'info' in e:
log.debug(
"FreeNAS_LDAP_Directory[ERROR]: info: '%s'",
e['info']
)
if 'desc' in e:
log.debug(
"FreeNAS_LDAP_Directory[ERROR]: desc: '%s'",
e['desc']
)
def isOpen(self):
return self._isopen
def _geturi(self):
if self.host is None:
return None
uri = None
if self.ssl in (FREENAS_LDAP_NOSSL, FREENAS_LDAP_USETLS):
proto = "ldap"
elif self.ssl == FREENAS_LDAP_USESSL:
proto = "ldaps"
else:
proto = "ldap"
uri = "%s://%s:%d" % (proto, self.host, self.port)
return uri
def _do_authenticated_bind(self):
if DS_DEBUG:
log.debug(
"FreeNAS_LDAP_Directory.open: "
"(authenticated bind) trying to bind to %s:%d",
self.host, self.port
)
return self._handle.simple_bind_s(self.binddn, self.bindpw)
def _do_anonymous_bind(self):
if DS_DEBUG:
log.debug(
"FreeNAS_LDAP_Directory.open: "
"(anonymous bind) trying to bind to %s:%d",
self.host, self.port
)
return self._handle.simple_bind_s()
def _do_sasl_gssapi_bind(self):
if DS_DEBUG:
log.debug(
"FreeNAS_LDAP_Directory.open: "
"(sasl gssapi bind) trying to bind to %s:%d",
self.host, self.port
)
auth_tokens = ldap.sasl.gssapi()
res = self._handle.sasl_interactive_bind_s('', auth_tokens)
if res == 0:
if DS_DEBUG:
log.debug(
"FreeNAS_LDAP_Directory.open: (sasl gssapi bind) successful"
)
return True
log.debug(
"FreeNAS_LDAP_Directory.open: "
"SASL/GSSAPI bind failed, trying simple bind"
)
if self.binddn and self.bindpw:
res = self._do_authenticated_bind()
if res:
return res
log.debug(
"FreeNAS_LDAP_Directory.open: "
"authenticated bind failed, trying simple bind"
)
return self._do_anonymous_bind()
def open(self):
if self._isopen:
return True
if self.host:
uri = self._geturi()
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Directory.open: uri = %s", uri)
self._handle = ldap.initialize(self._geturi())
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Directory.open: initialized")
if self._handle:
res = None
ldap.protocol_version = FREENAS_LDAP_VERSION
ldap.set_option(ldap.OPT_REFERRALS, FREENAS_LDAP_REFERRALS)
ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 10.0)
if self.ssl in (FREENAS_LDAP_USESSL, FREENAS_LDAP_USETLS):
ldap.set_option(ldap.OPT_X_TLS_ALLOW, 1)
if self.certfile:
ldap.set_option(
ldap.OPT_X_TLS_CACERTFILE,
self.certfile
)
ldap.set_option(
ldap.OPT_X_TLS_REQUIRE_CERT,
ldap.OPT_X_TLS_ALLOW
)
if self.ssl == FREENAS_LDAP_USETLS:
try:
self._handle.start_tls_s()
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Directory.open: started TLS")
except ldap.LDAPError as e:
self._logex(e)
raise e
bind_method = None
if self.anonbind:
bind_method = self._do_anonymous_bind
elif self.flags & FLAGS_SASL_GSSAPI:
bind_method = self._do_sasl_gssapi_bind
elif self.binddn and self.bindpw:
bind_method = self._do_authenticated_bind
else:
bind_method = self._do_anonymous_bind
try:
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Directory.open: trying to bind")
res = bind_method()
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Directory.open: binded")
except ldap.LDAPError as e:
log.debug(
"FreeNAS_LDAP_Directory.open: "
"could not bind to %s:%d (%s)",
self.host, self.port, e
)
self._logex(e)
res = None
raise e
if res:
self._isopen = True
log.debug("FreeNAS_LDAP_Directory.open: connection open")
return (self._isopen is True)
def unbind(self):
if self._handle:
self._handle.unbind()
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Directory.unbind: unbind")
def close(self):
if self._isopen:
self.unbind()
self._handle = None
self._isopen = False
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Directory.close: connection closed")
def _search(
self, basedn="", scope=ldap.SCOPE_SUBTREE, filter=None,
attributes=None, attrsonly=0, serverctrls=None, clientctrls=None,
timeout=-1, sizelimit=0
):
if DS_DEBUG:
log.debug(
"FreeNAS_LDAP_Directory._search: basedn = '%s', filter = '%s'",
basedn, filter
)
if not self._isopen:
return None
#
# XXX
# For some reason passing attributes causes paged search results
# to hang/fail after a a certain numbe of pages. I can't figure
# out why. This is a workaround.
# XXX
#
attributes = None
if not filter:
filter = ''
result = []
results = []
paged = SimplePagedResultsControl(
criticality=False,
size=self.pagesize,
cookie=''
)
paged_ctrls = {
SimplePagedResultsControl.controlType: SimplePagedResultsControl,
}
if self.pagesize > 0:
if DS_DEBUG:
log.debug(
"FreeNAS_LDAP_Directory._search: pagesize = %d",
self.pagesize
)
page = 0
while True:
if DS_DEBUG:
log.debug(
"FreeNAS_LDAP_Directory._search: getting page %d",
page
)
serverctrls = [paged]
id = self._handle.search_ext(
basedn,
scope,
filterstr=filter,
attrlist=attributes,
attrsonly=attrsonly,
serverctrls=serverctrls,
clientctrls=clientctrls,
timeout=timeout,
sizelimit=sizelimit
)
(rtype, rdata, rmsgid, serverctrls) = self._handle.result3(
id, resp_ctrl_classes=paged_ctrls
)
result.extend(rdata)
paged.size = 0
paged.cookie = cookie = None
for sc in serverctrls:
if sc.controlType == SimplePagedResultsControl.controlType:
cookie = sc.cookie
if cookie:
paged.cookie = cookie
paged.size = self.pagesize
break
if not cookie:
break
page += 1
else:
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Directory._search: pagesize = 0")
id = self._handle.search_ext(
basedn,
scope,
filterstr=filter,
attrlist=attributes,
attrsonly=attrsonly,
serverctrls=serverctrls,
clientctrls=clientctrls,
timeout=timeout,
sizelimit=sizelimit
)
type = ldap.RES_SEARCH_ENTRY
while type != ldap.RES_SEARCH_RESULT:
try:
type, data = self._handle.result(id, 0)
except ldap.LDAPError as e:
self._logex(e)
break
results.append(data)
for i in range(len(results)):
for entry in results[i]:
result.append(entry)
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Directory._search: %d results", len(result))
return result
def search(self):
isopen = self._isopen
self.open()
results = self._search(
self.basedn, self.scope, self.filter, self.attributes
)
if not isopen:
self.close()
return results
def _modify(self, dn, modlist):
if not self._isopen:
return None
res = self._handle.modify_ext_s(dn, modlist)
return res
def modify(self, dn, modlist):
isopen = self._isopen
self.open()
res = self._modify(dn, modlist)
if not isopen:
self.close()
return res
class FreeNAS_LDAP_Base(FreeNAS_LDAP_Directory):
def __keys(self):
return [
'hostname',
'host',
'port',
'anonbind',
'binddn',
'bindpw',
'basedn',
'ssl',
'usersuffix',
'groupsuffix',
'machinesuffix',
'passwordsuffix',
'sudosuffix',
'certfile',
'use_default_domain',
'has_samba_schema',
'kerberos_realm',
'krb_realm',
'krb_kdc',
'krb_admin_server',
'krb_kpasswd_server',
'kerberos_keytab',
'keytab_principal',
'keytab_file',
'idmap_backend',
'timeout',
'dns_timeout'
]
def __set_defaults(self):
for key in self.__keys():
if key in ('anonbind', 'use_default_domain'):
self.__dict__[key] = False
elif key in ('timeout', 'dns_timeout'):
self.__dict__[key] = 10
else:
self.__dict__[key] = None
self.flags = 0
def __name_to_host(self, name):
host = None
port = 389
if name:
parts = name.split(':')
host = parts[0]
if len(parts) > 1:
port = int(parts[1])
return (host, port)
def __init__(self, **kwargs):
self.kwargs = kwargs
self.__set_defaults()
if 'flags' in kwargs and (kwargs['flags'] & FLAGS_DBINIT):
ldap = ldap_objects()[0]
for key in list(ldap.__dict__.keys()):
if not key.startswith("ldap_"):
continue
newkey = key.replace("ldap_", "")
if newkey == 'hostname':
(host, port) = self.__name_to_host(ldap.__dict__[key])
if 'host' not in kwargs:
kwargs['host'] = host
if 'port' not in kwargs:
kwargs['port'] = port
kwargs[newkey] = ldap.__dict__[key]
if ldap.__dict__['ldap_ssl'] == FREENAS_LDAP_USESSL:
kwargs['port'] = 636
elif newkey in (
'anonbind', 'use_default_domain', 'has_samba_schema'
):
if 'anonbind' not in kwargs:
kwargs[newkey] = (
False if int(ldap.__dict__[key]) == 0 else True
)
elif 'use_default_domain' not in kwargs:
kwargs[newkey] = (
False if int(ldap.__dict__[key]) == 0 else True
)
elif 'has_samba_schema' not in kwargs:
kwargs[newkey] = (
False if int(ldap.__dict__[key]) == 0 else True
)
elif newkey == 'certificate_id':
cert = None
if ldap.ldap_certificate:
with client as c:
cert = c.call(
'certificate.query',
[['id', '=', ldap.ldap_certificate.id]],
{'get': True}
)
kwargs['certfile'] = cert['certificate_path'] if cert else cert
elif newkey == 'kerberos_realm_id':
kr = ldap.ldap_kerberos_realm
if kr:
kwargs['kerberos_realm'] = kr
kwargs['krb_realm'] = kr.krb_realm
kwargs['krb_kdc'] = kr.krb_kdc
kwargs['krb_admin_server'] = kr.krb_admin_server
kwargs['krb_kpasswd_server'] = kr.krb_kpasswd_server
elif newkey == 'kerberos_principal_id':
kp = ldap.ldap_kerberos_principal
if kp:
kwargs['kerberos_principal'] = kp
kwargs['keytab_principal'] = kp.principal_name
kwargs['keytab_file'] = '/etc/kerberos/%s' % kp.principal_keytab.keytab_name
else:
if newkey not in kwargs:
kwargs[newkey] = (
ldap.__dict__[key] if ldap.__dict__[key] else None
)
for key in kwargs:
if key == 'flags':
flags = self.flags
flags |= int(kwargs[key])
self.__dict__[key] = flags
elif key in self.__keys():
self.__dict__[key] = kwargs[key]
super(FreeNAS_LDAP_Base, self).__init__(**kwargs)
if self.kerberos_realm or self.keytab_principal:
self.get_kerberos_ticket()
self.flags |= FLAGS_SASL_GSSAPI
self.ucount = 0
self.gcount = 0
def kerberos_cache_has_ticket(self):
res = False
p = pipeopen("/usr/bin/klist -t")
p.communicate()
if p.returncode == 0:
res = True
return res
def get_kerberos_principal_from_cache(self):
principal = None
p = pipeopen("klist")
klist_out = p.communicate()
if p.returncode != 0:
return None
klist_out = klist_out[0]
lines = klist_out.splitlines()
for line in lines:
line = line.strip()
if line.startswith("Principal"):
parts = line.split(':')
if len(parts) > 1:
principal = parts[1].strip()
return principal
def get_kerberos_ticket(self):
res = False
kinit = False
if self.keytab_principal:
krb_principal = self.get_kerberos_principal_from_cache()
if (
krb_principal and
krb_principal.upper() == self.keytab_principal.upper()
):
return True
args = [
"/usr/bin/kinit",
"--renewable",
"-k",
"-t",
self.keytab_file,
self.keytab_principal
]
(returncode, stdout, stderr) = run(' '.join(args), timeout=self.timeout)
if returncode == 0:
kinit = True
res = True
elif self.krb_realm and self.binddn and self.bindpw:
user = self.get_user_by_DN(self.binddn)
try:
uid = user[1]['uid'][0].decode('utf-8')
except Exception:
uid = user[1]['uid'][0]
try:
bindpw = self.bindpw.encode('utf-8')
except Exception:
bindpw = self.bindpw
krb_principal = self.get_kerberos_principal_from_cache()
principal = "%s@%s" % (uid, self.krb_realm)
if krb_principal and krb_principal.upper() == principal.upper():
return True
(fd, fname) = tempfile.mkstemp(dir="/tmp", text=True)
os.write(fd, bindpw)
os.fchmod(fd, 0o777)
os.close(fd)
args = [
"/usr/bin/kinit",
"--renewable",
"--password-file=%s" % fname,
"%s" % principal
]
(returncode, stdout, stderr) = run(' '.join(args), timeout=self.timeout)
if returncode == 0:
kinit = True
res = True
os.unlink(fname)
if kinit:
i = 0
while i < self.timeout:
if self.kerberos_cache_has_ticket():
res = True
break
time.sleep(1)
i += 1
return res
def get_user_by_DN(self, DN):
if DS_DEBUG:
log.debug("FreeNAS_LDAP_Base.get_user_by_DN: DN = %s", DN)
if DN is None:
raise AssertionError('DN is None')
isopen = self._isopen
self.open()
ldap_user = None
scope = ldap.SCOPE_SUBTREE
basedn = DN
args = {'scope': scope, 'filter': '(objectclass=*)'}
if basedn:
args['basedn'] = basedn
if self.attributes:
args['attributes'] = self.attributes
results = self._search(**args)
if results:
for r in results:
if r[0]:
ldap_user = r
break
if not isopen:
self.close()
return ldap_user
def get_user(self, user):
log.debug("FreeNAS_LDAP_Base.get_user: user = %s", user)
if user is None:
raise AssertionError('user is None')
isopen = self._isopen
self.open()
ldap_user = None
scope = ldap.SCOPE_SUBTREE
if isinstance(user, int):
filter = '(&(|(objectclass=person)' \
'(objectclass=posixaccount)' \
'(objectclass=account))' \
'(uidnumber=%d))' % user
elif user.isdigit():
filter = '(&(|(objectclass=person)' \
'(objectclass=posixaccount)' \
'(objectclass=account))' \
'(uidnumber=%s))' % user
else:
filter = (
'(&(|(objectclass=person)'
'(objectclass=posixaccount)'
'(objectclass=account))'
'(|(uid=%s)(cn=%s)))'
) % (user, user)
basedn = None
if self.usersuffix and self.basedn:
basedn = "%s,%s" % (self.usersuffix, self.basedn)
elif self.basedn:
basedn = "%s" % self.basedn
args = {'scope': scope, 'filter': filter}
if basedn:
args['basedn'] = basedn
if self.attributes:
args['attributes'] = self.attributes
results = self._search(**args)
if results:
for r in results:
if r[0]:
ldap_user = r
break
if not isopen:
self.close()
return ldap_user
def get_users(self):
isopen = self._isopen
self.open()
users = []
scope = ldap.SCOPE_SUBTREE
filter = '(&(|(objectclass=person)' \
'(objectclass=posixaccount)' \
'(objectclass=account))(uid=*))'
if self.usersuffix:
basedn = "%s,%s" % (self.usersuffix, self.basedn)
else:
basedn = "%s" % self.basedn
results = self._search(basedn, scope, filter, self.attributes)
if results:
for r in results:
if r[0]:
users.append(r)
if not isopen:
self.close()
return users
def get_group(self, group):
log.debug("FreeNAS_LDAP_Base.get_group: group = %s", group)
if group is None:
raise AssertionError('group is None')
isopen = self._isopen
self.open()
ldap_group = None
scope = ldap.SCOPE_SUBTREE
if isinstance(group, int):
filter = '(&(|(objectclass=posixgroup)' \
'(objectclass=group))' \
'(gidnumber=%d))' % group
elif group.isdigit():
filter = '(&(|(objectclass=posixgroup)' \
'(objectclass=group))' \
'(gidnumber=%s))' % group
else:
filter = '(&(|(objectclass=posixgroup)' \
'(objectclass=group))' \
'(cn=%s))' % group
if self.groupsuffix:
basedn = "%s,%s" % (self.groupsuffix, self.basedn)
else:
basedn = "%s" % self.basedn
results = self._search(basedn, scope, filter, self.attributes)
if results:
for r in results:
if r[0]:
ldap_group = r
break
if not isopen:
self.close()
return ldap_group
def get_groups(self):
isopen = self._isopen
self.open()
groups = []
scope = ldap.SCOPE_SUBTREE
filter = '(&(|(objectclass=posixgroup)' \
'(objectclass=group))' \
'(gidnumber=*))'
if self.groupsuffix:
basedn = "%s,%s" % (self.groupsuffix, self.basedn)
else:
basedn = "%s" % self.basedn
results = self._search(basedn, scope, filter, self.attributes)
if results:
for r in results:
if r[0]:
groups.append(r)
if not isopen:
self.close()
return groups
def get_domains(self):
isopen = self._isopen
self.open()
domains = []
scope = ldap.SCOPE_SUBTREE
filter = '(objectclass=sambaDomain)'
results = self._search(self.basedn, scope, filter, self.attributes)
if results:
domains = results
if not isopen:
self.close()
return domains
def get_domain_names(self):
domain_names = []
domains = self.get_domains()
if domains:
for d in domains:
domain_names.append(d[1]['sambaDomainName'][0])
return domain_names
def has_samba_schema(self):
isopen = self._isopen
self.open()
ret = False
scope = ldap.SCOPE_SUBTREE
filter = '(objectclass=sambaDomain)'
results = self._search(self.basedn, scope, filter, self.attributes)
if results:
ret = True
if not isopen:
self.close()
return ret
class FreeNAS_LDAP(FreeNAS_LDAP_Base):
def __init__(self, **kwargs):
super(FreeNAS_LDAP, self).__init__(**kwargs)