/
forms.py
1132 lines (953 loc) · 35.6 KB
/
forms.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 2014 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 base64
import logging
import os
import re
import tempfile
from ldap import LDAPError
from django.core.exceptions import ObjectDoesNotExist
from django.forms import FileField
from django.utils.translation import ugettext_lazy as _
from dojango import forms
from freenasUI.common.forms import ModelForm
from freenasUI.common.freenasldap import (
FreeNAS_ActiveDirectory,
FreeNAS_LDAP,
)
from freenasUI.common.freenassysctl import freenas_sysctl as _fs
from freenasUI.common.pipesubr import run
from freenasUI.common.system import (
validate_netbios_name,
compare_netbios_names
)
from freenasUI.directoryservice import models, utils
from freenasUI.middleware.client import client
from freenasUI.middleware.exceptions import MiddlewareError
from freenasUI.middleware.form import MiddlewareModelForm
from freenasUI.middleware.notifier import notifier
from freenasUI.services.models import CIFS, ServiceMonitor
log = logging.getLogger('directoryservice.form')
class idmap_ad_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_ad
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_adex_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_adex
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_autorid_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_autorid
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_fruit_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_fruit
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_hash_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_hash
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_ldap_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_ldap
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_nss_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_nss
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_rfc2307_Form(ModelForm):
idmap_rfc2307_ldap_user_dn_password2 = forms.CharField(
max_length=120,
label=_("Confirm LDAP User DN Password"),
widget=forms.widgets.PasswordInput(),
required=False
)
class Meta:
fields = [
'idmap_rfc2307_range_low',
'idmap_rfc2307_range_high',
'idmap_rfc2307_ldap_server',
'idmap_rfc2307_bind_path_user',
'idmap_rfc2307_bind_path_group',
'idmap_rfc2307_user_cn',
'idmap_rfc2307_cn_realm',
'idmap_rfc2307_ldap_domain',
'idmap_rfc2307_ldap_url',
'idmap_rfc2307_ldap_user_dn',
'idmap_rfc2307_ldap_user_dn_password',
'idmap_rfc2307_ldap_user_dn_password2',
'idmap_rfc2307_ldap_realm',
'idmap_rfc2307_ssl',
'idmap_rfc2307_certificate'
]
model = models.idmap_rfc2307
widgets = {
'idmap_rfc2307_ldap_user_dn_password':
forms.widgets.PasswordInput(render_value=False)
}
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
def __init__(self, *args, **kwargs):
super(idmap_rfc2307_Form, self).__init__(*args, **kwargs)
if self.instance.idmap_rfc2307_ldap_user_dn_password:
self.fields['idmap_rfc2307_ldap_user_dn_password'].required = False
if self._api is True:
del self.fields['idmap_rfc2307_ldap_user_dn_password']
def clean_idmap_rfc2307_ldap_user_dn_password2(self):
password1 = self.cleaned_data.get("idmap_rfc2307_ldap_user_dn_password")
password2 = self.cleaned_data.get("idmap_rfc2307_ldap_user_dn_password2")
if password1 != password2:
raise forms.ValidationError(
_("The two password fields didn't match.")
)
return password2
def clean(self):
cdata = self.cleaned_data
if not cdata.get("idmap_rfc2307_ldap_user_dn_password"):
cdata['idmap_rfc2307_ldap_user_dn_password'] = \
self.instance.idmap_rfc2307_ldap_user_dn_password
return cdata
class idmap_rid_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_rid
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_tdb_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_tdb
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_tdb2_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_tdb2
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class idmap_script_Form(ModelForm):
class Meta:
fields = '__all__'
model = models.idmap_script
exclude = [
'idmap_ds_type',
'idmap_ds_id'
]
class ActiveDirectoryForm(ModelForm):
ad_netbiosname_a = forms.CharField(
max_length=120,
label=_("NetBIOS name"),
)
ad_netbiosname_b = forms.CharField(
max_length=120,
label=_("NetBIOS name"),
)
ad_netbiosalias = forms.CharField(
max_length=120,
label=_("NetBIOS alias"),
required=False,
)
advanced_fields = [
'ad_netbiosname_a',
'ad_netbiosname_b',
'ad_netbiosalias',
'ad_ssl',
'ad_certificate',
'ad_verbose_logging',
'ad_unix_extensions',
'ad_allow_trusted_doms',
'ad_use_default_domain',
'ad_allow_dns_updates',
'ad_disable_freenas_cache',
'ad_userdn',
'ad_groupdn',
'ad_site',
'ad_dcname',
'ad_gcname',
'ad_kerberos_realm',
'ad_kerberos_principal',
'ad_nss_info',
'ad_timeout',
'ad_dns_timeout',
'ad_idmap_backend',
'ad_ldap_sasl_wrapping'
]
class Meta:
fields = '__all__'
exclude = ['ad_idmap_backend_type', 'ad_userdn', 'ad_groupdn']
model = models.ActiveDirectory
widgets = {
'ad_bindpw': forms.widgets.PasswordInput(render_value=False),
}
def __original_save(self):
for name in (
'ad_domainname',
'ad_allow_trusted_doms',
'ad_use_default_domain',
'ad_unix_extensions',
'ad_verbose_logging',
'ad_bindname',
'ad_bindpw'
):
setattr(
self.instance,
"_original_%s" % name,
getattr(self.instance, name)
)
for name in (
'cifs_srv_netbiosname',
'cifs_srv_netbiosname_b',
'cifs_srv_netbiosalias',
):
setattr(
self.cifs,
"_original_%s" % name,
getattr(self.cifs, name),
)
def __original_changed(self):
if (
self.instance._original_ad_domainname != self.instance.ad_domainname or
self.cifs._original_cifs_srv_netbiosname != self.cifs.cifs_srv_netbiosname or
self.cifs._original_cifs_srv_netbiosname_b != self.cifs.cifs_srv_netbiosname_b or
self.cifs._original_cifs_srv_netbiosalias != self.cifs.cifs_srv_netbiosalias or
self.instance._original_ad_allow_trusted_doms != self.instance.ad_allow_trusted_doms or
self.instance._original_ad_use_default_domain != self.instance.ad_use_default_domain or
self.instance._original_ad_unix_extensions != self.instance.ad_unix_extensions or
self.instance._original_ad_verbose_logging != self.instance.ad_verbose_logging or
self.instance._original_ad_bindname != self.instance.ad_bindname or
self.instance._original_ad_bindpw != self.instance.ad_bindpw
):
return True
return False
def __init__(self, *args, **kwargs):
super(ActiveDirectoryForm, self).__init__(*args, **kwargs)
if self.instance.ad_bindpw:
self.fields['ad_bindpw'].required = False
self.cifs = CIFS.objects.latest('id')
self.__original_save()
self.fields["ad_idmap_backend"].widget.attrs["onChange"] = (
"activedirectory_idmap_check();"
)
self.fields["ad_enable"].widget.attrs["onChange"] = (
"activedirectory_mutex_toggle();"
)
if self.cifs:
self.fields['ad_netbiosname_a'].initial = self.cifs.cifs_srv_netbiosname
self.fields['ad_netbiosname_b'].initial = self.cifs.cifs_srv_netbiosname_b
self.fields['ad_netbiosalias'].initial = self.cifs.cifs_srv_netbiosalias
_n = notifier()
if not _n.is_freenas():
if _n.failover_licensed():
from freenasUI.failover.utils import node_label_field
node_label_field(
_n.failover_node(),
self.fields['ad_netbiosname_a'],
self.fields['ad_netbiosname_b'],
)
else:
del self.fields['ad_netbiosname_b']
else:
del self.fields['ad_netbiosname_b']
def get_dcport(self):
ad_dcname = self.cleaned_data.get('ad_dcname')
ad_dcport = 389
ad_ssl = self.cleaned_data.get('ad_ssl')
if ad_ssl == 'on':
ad_dcport = 636
if not ad_dcname:
return ad_dcport
parts = ad_dcname.split(':')
if len(parts) > 1 and parts[1].isdigit():
ad_dcport = int(parts[1])
return ad_dcport
def clean_ad_dcname(self):
ad_dcname = self.cleaned_data.get('ad_dcname')
ad_dcport = self.get_dcport()
if not ad_dcname:
return None
parts = ad_dcname.split(':')
ad_dcname = parts[0]
errors = []
try:
ret = FreeNAS_ActiveDirectory.port_is_listening(
host=ad_dcname, port=ad_dcport, errors=errors
)
if ret is False:
raise Exception(
'Invalid Host/Port: %s' % errors[0]
)
except Exception as e:
raise forms.ValidationError('%s.' % e)
return self.cleaned_data.get('ad_dcname')
def get_gcport(self):
ad_gcname = self.cleaned_data.get('ad_gcname')
ad_gcport = 3268
ad_ssl = self.cleaned_data.get('ad_ssl')
if ad_ssl == 'on':
ad_gcport = 3269
if not ad_gcname:
return ad_gcport
parts = ad_gcname.split(':')
if len(parts) > 1 and parts[1].isdigit():
ad_gcport = int(parts[1])
return ad_gcport
def clean_ad_gcname(self):
ad_gcname = self.cleaned_data.get('ad_gcname')
ad_gcport = self.get_gcport()
if not ad_gcname:
return None
parts = ad_gcname.split(':')
ad_gcname = parts[0]
errors = []
try:
ret = FreeNAS_ActiveDirectory.port_is_listening(
host=ad_gcname, port=ad_gcport, errors=errors
)
if ret is False:
raise Exception(
'Invalid Host/Port: %s' % errors[0]
)
except Exception as e:
raise forms.ValidationError('%s.' % e)
return self.cleaned_data.get('ad_gcname')
def clean_ad_netbiosname_a(self):
netbiosname = self.cleaned_data.get("ad_netbiosname_a")
try:
validate_netbios_name(netbiosname)
except Exception as e:
raise forms.ValidationError(e)
return netbiosname
def clean_ad_netbiosname_b(self):
netbiosname_a = self.cleaned_data.get("ad_netbiosname_a")
netbiosname = self.cleaned_data.get("ad_netbiosname_b")
if not netbiosname:
return netbiosname
if netbiosname_a and netbiosname_a == netbiosname:
with client as c:
system_dataset = c.call('systemdataset.config')
if system_dataset['path'] == "freenas-boot":
raise forms.ValidationError(_(
'When the system dataset is located on the boot device, the same NetBIOS name cannot be used on both controllers.'
))
try:
validate_netbios_name(netbiosname)
except Exception as e:
raise forms.ValidationError(e)
return netbiosname
def clean_ad_netbiosalias(self):
netbiosalias = self.cleaned_data.get("ad_netbiosalias")
if netbiosalias:
try:
validate_netbios_name(netbiosalias)
except Exception as e:
raise forms.ValidationError(e)
return netbiosalias
def clean(self):
cdata = self.cleaned_data
domain = cdata.get("ad_domainname")
bindname = cdata.get("ad_bindname")
binddn = "%s@%s" % (bindname, domain)
bindpw = cdata.get("ad_bindpw")
site = cdata.get("ad_site")
netbiosname = cdata.get("ad_netbiosname_a")
netbiosname_b = cdata.get("ad_netbiosname_b")
ssl = cdata.get("ad_ssl")
certificate = cdata["ad_certificate"]
ad_kerberos_principal = cdata["ad_kerberos_principal"]
workgroup = None
if certificate:
with client as c:
certificate = c.call(
'certificate.query',
[['id', '=', certificate.id]],
{'get': True}
)
certificate = certificate['certificate_path']
args = {
'domain': domain,
'site': site,
'ssl': ssl,
'certfile': certificate
}
if not cdata.get("ad_bindpw"):
bindpw = self.instance.ad_bindpw
cdata['ad_bindpw'] = bindpw
if cdata.get("ad_enable") is False:
return cdata
if not ad_kerberos_principal:
if not bindname:
raise forms.ValidationError("No domain account name specified")
if not bindpw:
raise forms.ValidationError("No domain account password specified")
try:
FreeNAS_ActiveDirectory.validate_credentials(
domain,
site=site,
ssl=ssl,
certfile=certificate,
binddn=binddn,
bindpw=bindpw
)
except LDAPError as e:
log.debug("LDAPError: type = %s", type(e))
error = []
try:
error.append(e.args[0]['info'])
error.append(e.args[0]['desc'])
error = ', '.join(error)
except Exception as e:
error = str(e)
raise forms.ValidationError("{0}".format(error))
except Exception as e:
log.debug("Exception: type = %s", type(e))
raise forms.ValidationError('{0}.'.format(str(e)))
args['binddn'] = binddn
args['bindpw'] = bindpw
else:
args['keytab_principal'] = ad_kerberos_principal.principal_name
args['keytab_file'] = '/etc/krb5.keytab'
try:
workgroup = FreeNAS_ActiveDirectory.get_workgroup_name(**args)
except Exception as e:
raise forms.ValidationError(e)
if workgroup:
if compare_netbios_names(netbiosname, workgroup, None):
raise forms.ValidationError(_(
"The NetBIOS name cannot be the same as the workgroup name!"
))
if netbiosname_b:
if compare_netbios_names(netbiosname_b, workgroup, None):
raise forms.ValidationError(_(
"The NetBIOS name cannot be the same as the workgroup "
"name!"
))
else:
log.warn("Unable to determine workgroup name")
if ssl in ("off", None):
return cdata
if not certificate:
raise forms.ValidationError(
"SSL/TLS specified without certificate")
return cdata
def save(self):
enable = self.cleaned_data.get("ad_enable")
enable_monitoring = self.cleaned_data.get("ad_enable_monitor")
monit_frequency = self.cleaned_data.get("ad_monitor_frequency")
monit_retry = self.cleaned_data.get("ad_recover_retry")
fqdn = self.cleaned_data.get("ad_domainname")
sm = None
if self.__original_changed():
notifier().clear_activedirectory_config()
started = notifier().started(
"activedirectory",
timeout=_fs().directoryservice.activedirectory.timeout.started
)
obj = super(ActiveDirectoryForm, self).save()
try:
utils.get_idmap_object(obj.ds_type, obj.id, obj.ad_idmap_backend)
except ObjectDoesNotExist:
log.debug(
'IDMAP backend {} entry does not exist, creating one.'.format(obj.ad_idmap_backend)
)
utils.get_idmap(obj.ds_type, obj.id, obj.ad_idmap_backend)
self.cifs.cifs_srv_netbiosname = self.cleaned_data.get("ad_netbiosname_a")
self.cifs.cifs_srv_netbiosname_b = self.cleaned_data.get("ad_netbiosname_b")
self.cifs.cifs_srv_netbiosalias = self.cleaned_data.get("ad_netbiosalias")
self.cifs.save()
if enable:
if started is True:
timeout = _fs().directoryservice.activedirectory.timeout.restart
try:
started = notifier().restart("activedirectory", timeout=timeout)
except Exception as e:
raise MiddlewareError(
_("Active Directory restart timed out after %d seconds." % timeout),
)
if started is False:
timeout = _fs().directoryservice.activedirectory.timeout.start
try:
started = notifier().start("activedirectory", timeout=timeout)
except Exception as e:
raise MiddlewareError(
_("Active Directory start timed out after %d seconds." % timeout),
)
if started is False:
self.instance.ad_enable = False
super(ActiveDirectoryForm, self).save()
raise MiddlewareError(
_("Active Directory failed to reload."),
)
else:
if started is True:
timeout = _fs().directoryservice.activedirectory.timeout.stop
try:
started = notifier().stop("activedirectory", timeout=timeout)
except Exception as e:
raise MiddlewareError(
_("Active Directory stop timed out after %d seconds." % timeout),
)
sm_name = 'activedirectory'
try:
sm = ServiceMonitor.objects.get(sm_name=sm_name)
except Exception as e:
log.debug("XXX: Unable to find ServiceMonitor: %s", e)
pass
#
# Ports can be specified in the UI but there doesn't appear to be a way to
# override them via SRV records. This should be fixed.
#
dcport = self.get_dcport()
# gcport = self.get_gcport()
if not sm:
try:
log.debug(
"XXX: fqdn=%s dcport=%s frequency=%s retry=%s enable=%s",
fqdn, dcport, monit_frequency,
monit_retry, enable_monitoring
)
sm = ServiceMonitor.objects.create(
sm_name=sm_name,
sm_host=fqdn,
sm_port=dcport,
sm_frequency=monit_frequency,
sm_retry=monit_retry,
sm_enable=enable_monitoring
)
except Exception as e:
log.debug("XXX: Unable to create ServiceMonitor: %s", e)
raise MiddlewareError(
_("Unable to create ServiceMonitor: %s" % e),
)
else:
sm.sm_name = sm_name
if fqdn != sm.sm_host:
sm.sm_host = fqdn
if dcport != sm.sm_port:
sm.sm_port = dcport
if monit_frequency != sm.sm_frequency:
sm.sm_frequency = monit_frequency
if monit_retry != sm.sm_retry:
sm.sm_retry = monit_retry
if enable_monitoring != sm.sm_enable:
sm.sm_enable = enable_monitoring
try:
sm.save(force_update=True)
except Exception as e:
log.debug("XXX: Unable to create ServiceMonitor: %s", e)
raise MiddlewareError(
_("Unable to save ServiceMonitor: %s" % e),
)
with client as c:
if enable_monitoring and enable:
log.debug("[ServiceMonitoring] Add %s service, frequency: %d, retry: %d" % ('activedirectory', monit_frequency, monit_retry))
c.call('servicemonitor.restart')
else:
log.debug("[ServiceMonitoring] Remove %s service, frequency: %d, retry: %d" % ('activedirectory', monit_frequency, monit_retry))
c.call('servicemonitor.restart')
return obj
class NISForm(MiddlewareModelForm, ModelForm):
middleware_attr_prefix = 'nis_'
middleware_attr_schema = 'nis'
middleware_plugin = 'nis'
is_singletone = True
class Meta:
fields = '__all__'
model = models.NIS
def __init__(self, *args, **kwargs):
super(NISForm, self).__init__(*args, **kwargs)
self.fields["nis_enable"].widget.attrs["onChange"] = (
"nis_mutex_toggle();"
)
def middleware_clean(self, data):
data['servers'] = data['servers'].split(',')
return data
class LDAPForm(ModelForm):
ldap_netbiosname_a = forms.CharField(
max_length=120,
label=_("NetBIOS name"),
)
ldap_netbiosname_b = forms.CharField(
max_length=120,
label=_("NetBIOS name"),
required=False,
)
ldap_netbiosalias = forms.CharField(
max_length=120,
label=_("NetBIOS alias"),
required=False,
)
advanced_fields = [
'ldap_anonbind',
'ldap_usersuffix',
'ldap_groupsuffix',
'ldap_passwordsuffix',
'ldap_machinesuffix',
'ldap_sudosuffix',
'ldap_netbiosname_a',
'ldap_netbiosname_b',
'ldap_netbiosalias',
'ldap_kerberos_realm',
'ldap_kerberos_principal',
'ldap_ssl',
'ldap_certificate',
'ldap_timeout',
'ldap_dns_timeout',
'ldap_idmap_backend',
'ldap_has_samba_schema',
'ldap_auxiliary_parameters',
'ldap_schema'
]
class Meta:
fields = '__all__'
exclude = ['ldap_idmap_backend_type']
model = models.LDAP
widgets = {
'ldap_bindpw': forms.widgets.PasswordInput(render_value=False),
}
def __init__(self, *args, **kwargs):
super(LDAPForm, self).__init__(*args, **kwargs)
self.fields["ldap_enable"].widget.attrs["onChange"] = (
"ldap_mutex_toggle();"
)
self.cifs = CIFS.objects.latest('id')
if self.cifs:
self.fields['ldap_netbiosname_a'].initial = self.cifs.cifs_srv_netbiosname
self.fields['ldap_netbiosname_b'].initial = self.cifs.cifs_srv_netbiosname_b
self.fields['ldap_netbiosalias'].initial = self.cifs.cifs_srv_netbiosalias
_n = notifier()
if not _n.is_freenas():
if _n.failover_licensed():
from freenasUI.failover.utils import node_label_field
node_label_field(
_n.failover_node(),
self.fields['ldap_netbiosname_a'],
self.fields['ldap_netbiosname_b'],
)
else:
del self.fields['ldap_netbiosname_b']
else:
del self.fields['ldap_netbiosname_b']
def check_for_samba_schema(self):
self.clean_bindpw()
cdata = self.cleaned_data
binddn = cdata.get("ldap_binddn")
bindpw = cdata.get("ldap_bindpw")
basedn = cdata.get("ldap_basedn")
hostname = cdata.get("ldap_hostname")
# TODO: Usage of this function has been commented, should it be removed ?
certfile = None
ssl = cdata.get("ldap_ssl")
if ssl in ('start_tls', 'on'):
certificate = cdata["ldap_certificate"]
if certificate:
with client as c:
certificate = c.call(
'certificate.query',
[['id', '=', certificate.id]],
{'get': True}
)
certfile = certificate['certificate_path'] if certificate else None
fl = FreeNAS_LDAP(
host=hostname,
binddn=binddn,
bindpw=bindpw,
basedn=basedn,
certfile=certfile,
ssl=ssl
)
if fl.has_samba_schema():
self.instance.ldap_has_samba_schema = True
else:
self.instance.ldap_has_samba_schema = False
def clean_ldap_netbiosname_a(self):
netbiosname = self.cleaned_data.get("ldap_netbiosname_a")
try:
validate_netbios_name(netbiosname)
except Exception as e:
raise forms.ValidationError(e)
return netbiosname
def clean_ldap_netbiosname_b(self):
netbiosname_a = self.cleaned_data.get("ldap_netbiosname_a")
netbiosname = self.cleaned_data.get("ldap_netbiosname_b")
if not netbiosname:
return netbiosname
if netbiosname_a and netbiosname_a == netbiosname:
raise forms.ValidationError(_(
'NetBIOS cannot be the same as the first.'
))
try:
validate_netbios_name(netbiosname)
except Exception as e:
raise forms.ValidationError(e)
return netbiosname
def clean_ldap_netbiosalias(self):
netbiosalias = self.cleaned_data.get("ldap_netbiosalias")
if netbiosalias:
try:
validate_netbios_name(netbiosalias)
except Exception as e:
raise forms.ValidationError(e)
return netbiosalias
def clean(self):
cdata = self.cleaned_data
if not cdata.get("ldap_bindpw"):
cdata["ldap_bindpw"] = self.instance.ldap_bindpw
binddn = cdata.get("ldap_binddn")
bindpw = cdata.get("ldap_bindpw")
basedn = cdata.get("ldap_basedn")
hostname = cdata.get("ldap_hostname")
ssl = cdata.get("ldap_ssl")
certfile = None
if ssl in ('start_tls', 'on'):
certificate = cdata["ldap_certificate"]
if not certificate:
raise forms.ValidationError(
"SSL/TLS specified without certificate")
else:
with client as c:
certificate = c.call(
'certificate.query',
[['id', '=', certificate.id]],
{'get': True}
)
certfile = certificate['certificate_path']
port = 389
if ssl == "on":
port = 636
if hostname:
parts = hostname.split(':')
hostname = parts[0]
if len(parts) > 1:
port = int(parts[1])
if cdata.get("ldap_enable") is False:
return cdata
# self.check_for_samba_schema()
try:
FreeNAS_LDAP.validate_credentials(
hostname,
binddn=binddn,
bindpw=bindpw,
basedn=basedn,
port=port,
certfile=certfile,
ssl=ssl
)
except LDAPError as e:
log.debug("LDAPError: type = %s", type(e))
error = []
try:
error.append(e.args[0]['info'])
error.append(e.args[0]['desc'])
error = ', '.join(error)
except Exception as e:
error = str(e)
raise forms.ValidationError("{0}".format(error))
except Exception as e:
log.debug("LDAPError: type = %s", type(e))
raise forms.ValidationError("{0}".format(str(e)))
return cdata
def save(self):
enable = self.cleaned_data.get("ldap_enable")
started = notifier().started("ldap")
obj = super(LDAPForm, self).save()
self.cifs.cifs_srv_netbiosname = self.cleaned_data.get("ldap_netbiosname_a")
self.cifs.cifs_srv_netbiosname_b = self.cleaned_data.get("ldap_netbiosname_b")
self.cifs.cifs_srv_netbiosalias = self.cleaned_data.get("ldap_netbiosalias")
self.cifs.save()
if enable:
if started is True:
started = notifier().restart("ldap", timeout=_fs().directoryservice.ldap.timeout.restart)
if started is False:
started = notifier().start("ldap", timeout=_fs().directoryservice.ldap.timeout.start)
if started is False:
self.instance.ldap_enable = False
super(LDAPForm, self).save()
raise MiddlewareError(_("LDAP failed to reload."))
else:
if started is True:
started = notifier().stop("ldap", timeout=_fs().directoryservice.ldap.timeout.stop)
return obj
def done(self, request, events):
events.append("refreshById('tab_LDAP')")
super(LDAPForm, self).done(request, events)
class KerberosRealmForm(ModelForm):
advanced_fields = [
'krb_kdc',
'krb_admin_server',
'krb_kpasswd_server'
]
class Meta:
fields = '__all__'
model = models.KerberosRealm
def clean_krb_realm(self):
krb_realm = self.cleaned_data.get("krb_realm", None)
if krb_realm:
krb_realm = krb_realm.upper()
return krb_realm
def save(self):
super(KerberosRealmForm, self).save()
notifier().start("ix-kerberos")
class KerberosKeytabCreateForm(ModelForm):