forked from freeipa/freeipa
-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.py
3640 lines (3103 loc) · 124 KB
/
client.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 (C) 2016 FreeIPA Contributors see COPYING for license
#
"""
IPA client install module
Provides methods for installation, uninstallation of IPA client
"""
from __future__ import (
print_function,
absolute_import,
)
import logging
import dns
import getpass
import gssapi
import netifaces
import os
import SSSDConfig
import socket
import sys
import tempfile
import time
import traceback
# pylint: disable=import-error
from six.moves.configparser import RawConfigParser
from six.moves.urllib.parse import urlparse, urlunparse
# pylint: enable=import-error
from ipalib import api, errors, x509
from ipalib.install import certmonger, certstore, service, sysrestore
from ipalib.install import hostname as hostname_
from ipalib.install.kinit import kinit_keytab, kinit_password
from ipalib.install.service import enroll_only, prepare_only
from ipalib.rpc import delete_persistent_client_session_data
from ipalib.util import (
normalize_hostname,
no_matching_interface_for_ip_address_warning,
verify_host_resolvable,
)
from ipaplatform import services
from ipaplatform.paths import paths
from ipaplatform.tasks import tasks
from ipapython import certdb, kernel_keyring, ipaldap, ipautil
from ipapython.admintool import ScriptError
from ipapython.dn import DN
from ipapython.install import typing
from ipapython.install.core import group, knob, extend_knob
from ipapython.install.common import step
from ipapython.ipautil import (
CalledProcessError,
realm_to_suffix,
run,
user_input,
)
from ipapython.ssh import SSHPublicKey
from . import automount, ipadiscovery, ntpconf, sssd
from .ipachangeconf import IPAChangeConf
NoneType = type(None)
logger = logging.getLogger(__name__)
SUCCESS = 0
CLIENT_INSTALL_ERROR = 1
CLIENT_NOT_CONFIGURED = 2
CLIENT_ALREADY_CONFIGURED = 3
CLIENT_UNINSTALL_ERROR = 4 # error after restoring files/state
SECURE_PATH = (
"/bin:/sbin:/usr/kerberos/bin:/usr/kerberos/sbin:/usr/bin:/usr/sbin"
)
# global variables
hostname = None
hostname_source = None
nosssd_files = None
dnsok = False
cli_domain = None
cli_server = None
subject_base = None
cli_realm = None
cli_kdc = None
client_domain = None
cli_basedn = None
# end of global variables
def remove_file(filename):
"""
Deletes a file. If the file does not exist (OSError 2) does nothing.
Otherwise logs an error message and instructs the user to remove the
offending file manually
:param filename: name of the file to be removed
"""
try:
os.remove(filename)
except OSError as e:
if e.errno == 2:
return
logger.error("Failed to remove file %s: %s", filename, e)
logger.error('Please remove %s manually, as it can cause '
'subsequent installation to fail.', filename)
def log_service_error(name, action, error):
logger.error("%s failed to %s: %s", name, action, str(error))
def get_cert_path(cert_path):
"""
If a CA certificate is passed in on the command line, use that.
Else if a CA file exists in paths.IPA_CA_CRT then use that.
Otherwise return None.
"""
if cert_path is not None:
return cert_path
if os.path.exists(paths.IPA_CA_CRT):
return paths.IPA_CA_CRT
return None
def save_state(service, statestore):
enabled = service.is_enabled()
running = service.is_running()
if enabled or running:
statestore.backup_state(service.service_name, 'enabled', enabled)
statestore.backup_state(service.service_name, 'running', running)
def restore_state(service, statestore):
enabled = statestore.restore_state(service.service_name, 'enabled')
running = statestore.restore_state(service.service_name, 'running')
if enabled:
try:
service.enable()
except Exception:
logger.warning(
"Failed to configure automatic startup of the %s daemon",
service.service_name
)
if running:
try:
service.start()
except Exception:
logger.warning(
"Failed to restart the %s daemon",
service.service_name
)
def nssldap_exists():
"""Checks whether nss_ldap or nss-pam-ldapd is installed.
If anyone of mandatory files was found returns True and list of all files
found.
"""
files_to_check = [
{
'function': 'configure_ldap_conf',
'mandatory': [
paths.LDAP_CONF,
paths.NSS_LDAP_CONF,
paths.LIBNSS_LDAP_CONF],
'optional':[paths.PAM_LDAP_CONF]
},
{
'function': 'configure_nslcd_conf',
'mandatory': [paths.NSLCD_CONF]
}
]
files_found = {}
retval = False
for function in files_to_check:
files_found[function['function']] = []
for file_type in ['mandatory', 'optional']:
try:
for filename in function[file_type]:
if os.path.isfile(filename):
files_found[function['function']].append(filename)
if file_type == 'mandatory':
retval = True
except KeyError:
pass
return (retval, files_found)
def delete_ipa_domain():
"""Helper function for uninstall.
Deletes IPA domain from sssd.conf
"""
try:
sssdconfig = SSSDConfig.SSSDConfig()
sssdconfig.import_config()
domains = sssdconfig.list_active_domains()
ipa_domain_name = None
for name in domains:
domain = sssdconfig.get_domain(name)
try:
provider = domain.get_option('id_provider')
if provider == "ipa":
ipa_domain_name = name
break
except SSSDConfig.NoOptionError:
continue
if ipa_domain_name is not None:
sssdconfig.delete_domain(ipa_domain_name)
sssdconfig.write()
else:
logger.warning(
"IPA domain could not be found in "
"/etc/sssd/sssd.conf and therefore not deleted")
except IOError:
logger.warning(
"IPA domain could not be deleted. "
"No access to the /etc/sssd/sssd.conf file.")
def is_ipa_client_installed(fstore, on_master=False):
"""
Consider IPA client not installed if nothing is backed up
and default.conf file does not exist. If on_master is set to True,
the existence of default.conf file is not taken into consideration,
since it has been already created by ipa-server-install.
"""
installed = (
fstore.has_files() or (
not on_master and os.path.exists(paths.IPA_DEFAULT_CONF)
)
)
return installed
def configure_nsswitch_database(fstore, database, services, preserve=True,
append=True, default_value=()):
"""
Edits the specified nsswitch.conf database (e.g. passwd, group, sudoers)
to use the specified service(s).
Arguments:
fstore - FileStore to backup the nsswitch.conf
database - database configuration that should be ammended,
e.g. 'sudoers'
service - list of services that should be added, e.g. ['sss']
preserve - if True, the already configured services will be preserved
The next arguments modify the behaviour if preserve=True:
append - if True, the services will be appended, if False, prepended
default_value - list of services that are considered as default (if
the database is not mentioned in nsswitch.conf), e.g.
['files']
"""
# Backup the original version of nsswitch.conf, we're going to edit it now
if not fstore.has_file(paths.NSSWITCH_CONF):
fstore.backup_file(paths.NSSWITCH_CONF)
conf = IPAChangeConf("IPA Installer")
conf.setOptionAssignment(':')
if preserve:
# Read the existing configuration
with open(paths.NSSWITCH_CONF, 'r') as f:
opts = conf.parse(f)
raw_database_entry = conf.findOpts(opts, 'option', database)[1]
# Detect the list of already configured services
if not raw_database_entry:
# If there is no database entry, database is not present in
# the nsswitch.conf. Set the list of services to the
# default list, if passed.
configured_services = list(default_value)
else:
configured_services = raw_database_entry['value'].strip().split()
# Make sure no service is added if already mentioned in the list
added_services = [s for s in services
if s not in configured_services]
# Prepend / append the list of new services
if append:
new_value = ' ' + ' '.join(configured_services + added_services)
else:
new_value = ' ' + ' '.join(added_services + configured_services)
else:
# Preserve not set, let's rewrite existing configuration
new_value = ' ' + ' '.join(services)
# Set new services as sources for database
opts = [
conf.setOption(database, new_value),
conf.emptyLine(),
]
conf.changeConf(paths.NSSWITCH_CONF, opts)
logger.info("Configured %s in %s", database, paths.NSSWITCH_CONF)
def configure_ipa_conf(
fstore, cli_basedn, cli_realm, cli_domain, cli_server, hostname):
ipaconf = IPAChangeConf("IPA Installer")
ipaconf.setOptionAssignment(" = ")
ipaconf.setSectionNameDelimiters(("[", "]"))
opts = [
{
'name': 'comment',
'type': 'comment',
'value': 'File modified by ipa-client-install'
},
ipaconf.emptyLine(),
]
# [global]
defopts = [
ipaconf.setOption('basedn', cli_basedn),
ipaconf.setOption('realm', cli_realm),
ipaconf.setOption('domain', cli_domain),
ipaconf.setOption('server', cli_server[0]),
ipaconf.setOption('host', hostname),
ipaconf.setOption('xmlrpc_uri',
'https://{}/ipa/xml'.format(
ipautil.format_netloc(cli_server[0]))),
ipaconf.setOption('enable_ra', 'True')
]
opts.extend([
ipaconf.setSection('global', defopts),
ipaconf.emptyLine(),
])
target_fname = paths.IPA_DEFAULT_CONF
fstore.backup_file(target_fname)
ipaconf.newConf(target_fname, opts)
# umask applies when creating a new file but we want 0o644 here
os.chmod(target_fname, 0o644)
def disable_ra():
"""Set the enable_ra option in /etc/ipa/default.conf to False
Note that api.env will retain the old value (it is readonly).
"""
parser = RawConfigParser()
parser.read(paths.IPA_DEFAULT_CONF)
parser.set('global', 'enable_ra', 'False')
fp = open(paths.IPA_DEFAULT_CONF, 'w')
parser.write(fp)
fp.close()
def configure_ldap_conf(
fstore, cli_basedn, cli_realm, cli_domain, cli_server, dnsok, options,
files):
ldapconf = IPAChangeConf("IPA Installer")
ldapconf.setOptionAssignment(" ")
opts = [
{
'name': 'comment',
'type': 'comment',
'value': 'File modified by ipa-client-install'
},
ldapconf.emptyLine(),
ldapconf.setOption('ldap_version', '3'),
ldapconf.setOption('base', cli_basedn),
ldapconf.emptyLine(),
ldapconf.setOption(
'nss_base_passwd', '{dn}{suffix}'
.format(dn=DN(('cn', 'users'), ('cn', 'accounts'), cli_basedn),
suffix='?sub')),
ldapconf.setOption(
'nss_base_group', '{dn}{suffix}'
.format(dn=DN(('cn', 'groups'), ('cn', 'accounts'), cli_basedn),
suffix='?sub')),
ldapconf.setOption('nss_schema', 'rfc2307bis'),
ldapconf.setOption('nss_map_attribute', 'uniqueMember member'),
ldapconf.setOption('nss_initgroups_ignoreusers', 'root,dirsrv'),
ldapconf.emptyLine(),
ldapconf.setOption('nss_reconnect_maxsleeptime', '8'),
ldapconf.setOption('nss_reconnect_sleeptime', '1'),
ldapconf.setOption('bind_timelimit', '5'),
ldapconf.setOption('timelimit', '15'),
ldapconf.emptyLine(),
]
if not dnsok or options.force or options.on_master:
if options.on_master:
opts.append(ldapconf.setOption('uri', 'ldap://localhost'))
else:
opts.append(ldapconf.setOption('uri', 'ldap://{}'.format(
ipautil.format_netloc(cli_server[0]))))
else:
opts.append(ldapconf.setOption('nss_srv_domain', cli_domain))
opts.append(ldapconf.emptyLine())
# Depending on the release and distribution this may exist in any
# number of different file names, update what we find
for filename in files:
try:
fstore.backup_file(filename)
ldapconf.newConf(filename, opts)
except Exception as e:
logger.error("Creation of %s failed: %s", filename, str(e))
return (1, 'LDAP', filename)
if files:
return (0, 'LDAP', ', '.join(files))
return 0, None, None
def configure_nslcd_conf(
fstore, cli_basedn, cli_realm, cli_domain, cli_server, dnsok, options,
files):
nslcdconf = IPAChangeConf("IPA Installer")
nslcdconf.setOptionAssignment(" ")
opts = [
{
'name': 'comment',
'type': 'comment',
'value': 'File modified by ipa-client-install'
},
nslcdconf.emptyLine(),
nslcdconf.setOption('ldap_version', '3'),
nslcdconf.setOption('base', cli_basedn),
nslcdconf.emptyLine(),
nslcdconf.setOption('base passwd', str(
DN(('cn', 'users'), ('cn', 'accounts'), cli_basedn))),
nslcdconf.setOption('base group', str(
DN(('cn', 'groups'), ('cn', 'accounts'), cli_basedn))),
nslcdconf.setOption('timelimit', '15'),
nslcdconf.emptyLine(),
]
if not dnsok or options.force or options.on_master:
if options.on_master:
opts.append(nslcdconf.setOption('uri', 'ldap://localhost'))
else:
opts.append(nslcdconf.setOption('uri', 'ldap://{}'.format(
ipautil.format_netloc(cli_server[0]))))
else:
opts.append(nslcdconf.setOption('uri', 'DNS'))
opts.append(nslcdconf.emptyLine())
for filename in files:
try:
fstore.backup_file(filename)
nslcdconf.newConf(filename, opts)
except Exception as e:
logger.error("Creation of %s failed: %s", filename, str(e))
return (1, None, None)
nslcd = services.knownservices.nslcd
if nslcd.is_installed():
try:
nslcd.restart()
except Exception as e:
log_service_error(nslcd.service_name, 'restart', e)
try:
nslcd.enable()
except Exception as e:
logger.error(
"Failed to enable automatic startup of the %s daemon: %s",
nslcd.service_name, str(e))
else:
logger.debug(
"%s daemon is not installed, skip configuration",
nslcd.service_name)
return (0, None, None)
return (0, 'NSLCD', ', '.join(files))
def configure_openldap_conf(fstore, cli_basedn, cli_server):
ldapconf = IPAChangeConf("IPA Installer")
ldapconf.setOptionAssignment((" ", "\t"))
opts = [
{
'name': 'comment',
'type': 'comment',
'value': ' File modified by ipa-client-install'
},
ldapconf.emptyLine(),
{
'name': 'comment',
'type': 'comment',
'value': ' We do not want to break your existing configuration, '
'hence:'
},
# this needs to be kept updated if we change more options
{
'name': 'comment',
'type': 'comment',
'value': ' URI, BASE and TLS_CACERT have been added if they '
'were not set.'
},
{
'name': 'comment',
'type': 'comment',
'value': ' In case any of them were set, a comment has been '
'inserted and'
},
{
'name': 'comment',
'type': 'comment',
'value': ' "# CONF_NAME modified by IPA" added to the line '
'above.'
},
{
'name': 'comment',
'type': 'comment',
'value': ' To use IPA server with openLDAP tools, please comment '
'out your'
},
{
'name': 'comment',
'type': 'comment',
'value': ' existing configuration for these options and '
'uncomment the'
},
{
'name': 'comment',
'type': 'comment',
'value': ' corresponding lines generated by IPA.'
},
ldapconf.emptyLine(),
ldapconf.emptyLine(),
{
'action': 'addifnotset',
'name': 'URI',
'type': 'option',
'value': 'ldaps://{}'.format(cli_server[0])
},
{
'action': 'addifnotset',
'name': 'BASE',
'type': 'option',
'value': str(cli_basedn)
},
{
'action': 'addifnotset',
'name': 'TLS_CACERT',
'type': 'option',
'value': paths.IPA_CA_CRT
},
]
target_fname = paths.OPENLDAP_LDAP_CONF
fstore.backup_file(target_fname)
error_msg = "Configuring {path} failed with: {err}"
try:
ldapconf.changeConf(target_fname, opts)
except SyntaxError as e:
logger.info("Could not parse %s", target_fname)
logger.debug('%s', error_msg.format(path=target_fname, err=str(e)))
return False
except IOError as e:
logger.info("%s does not exist.", target_fname)
logger.debug('%s', error_msg.format(path=target_fname, err=str(e)))
return False
except Exception as e: # we do not want to fail in an optional step
logger.debug('%s', error_msg.format(path=target_fname, err=str(e)))
return False
os.chmod(target_fname, 0o644)
return True
def hardcode_ldap_server(cli_server):
"""
DNS Discovery didn't return a valid IPA server, hardcode a value into
the file instead.
"""
if not os.path.isfile(paths.LDAP_CONF):
return
ldapconf = IPAChangeConf("IPA Installer")
ldapconf.setOptionAssignment(" ")
opts = [
ldapconf.setOption('uri', 'ldap://{}'.format(
ipautil.format_netloc(cli_server[0]))),
ldapconf.emptyLine(),
]
# Errors raised by this should be caught by the caller
ldapconf.changeConf(paths.LDAP_CONF, opts)
logger.info(
"Changed configuration of /etc/ldap.conf to use "
"hardcoded server name: %s", cli_server[0])
def configure_krb5_conf(
cli_realm, cli_domain, cli_server, cli_kdc, dnsok,
filename, client_domain, client_hostname, force=False,
configure_sssd=True):
krbconf = IPAChangeConf("IPA Installer")
krbconf.setOptionAssignment((" = ", " "))
krbconf.setSectionNameDelimiters(("[", "]"))
krbconf.setSubSectionDelimiters(("{", "}"))
krbconf.setIndent(("", " ", " "))
opts = [
{
'name': 'comment',
'type': 'comment',
'value': 'File modified by ipa-client-install'
},
krbconf.emptyLine(),
]
if os.path.exists(paths.COMMON_KRB5_CONF_DIR):
opts.extend([
{
'name': 'includedir',
'type': 'option',
'value': paths.COMMON_KRB5_CONF_DIR,
'delim': ' '
}
])
# SSSD include dir
if configure_sssd:
opts.extend([
{
'name': 'includedir',
'type': 'option',
'value': paths.SSSD_PUBCONF_KRB5_INCLUDE_D_DIR,
'delim': ' '
},
krbconf.emptyLine()])
# [libdefaults]
libopts = [
krbconf.setOption('default_realm', cli_realm)
]
if not dnsok or not cli_kdc or force:
libopts.extend([
krbconf.setOption('dns_lookup_realm', 'false'),
krbconf.setOption('dns_lookup_kdc', 'false')
])
else:
libopts.extend([
krbconf.setOption('dns_lookup_realm', 'true'),
krbconf.setOption('dns_lookup_kdc', 'true')
])
libopts.extend([
krbconf.setOption('rdns', 'false'),
krbconf.setOption('dns_canonicalize_hostname', 'false'),
krbconf.setOption('ticket_lifetime', '24h'),
krbconf.setOption('forwardable', 'true'),
krbconf.setOption('udp_preference_limit', '0')
])
# Configure KEYRING CCACHE if supported
if kernel_keyring.is_persistent_keyring_supported():
logger.debug("Enabling persistent keyring CCACHE")
libopts.append(krbconf.setOption('default_ccache_name',
'KEYRING:persistent:%{uid}'))
opts.extend([
krbconf.setSection('libdefaults', libopts),
krbconf.emptyLine()
])
# the following are necessary only if DNS discovery does not work
kropts = []
if not dnsok or not cli_kdc or force:
# [realms]
for server in cli_server:
kropts.extend([
krbconf.setOption('kdc', ipautil.format_netloc(server, 88)),
krbconf.setOption('master_kdc',
ipautil.format_netloc(server, 88)),
krbconf.setOption('admin_server',
ipautil.format_netloc(server, 749)),
krbconf.setOption('kpasswd_server',
ipautil.format_netloc(server, 464))
])
kropts.append(krbconf.setOption('default_domain', cli_domain))
kropts.append(
krbconf.setOption('pkinit_anchors',
'FILE:%s' % paths.KDC_CA_BUNDLE_PEM))
kropts.append(
krbconf.setOption('pkinit_pool',
'FILE:%s' % paths.CA_BUNDLE_PEM))
ropts = [{
'name': cli_realm,
'type': 'subsection',
'value': kropts
}]
opts.append(krbconf.setSection('realms', ropts))
opts.append(krbconf.emptyLine())
# [domain_realm]
dropts = [
krbconf.setOption('.{}'.format(cli_domain), cli_realm),
krbconf.setOption(cli_domain, cli_realm),
krbconf.setOption(client_hostname, cli_realm)
]
# add client domain mapping if different from server domain
if cli_domain != client_domain:
dropts.extend([
krbconf.setOption('.{}'.format(client_domain), cli_realm),
krbconf.setOption(client_domain, cli_realm)
])
opts.extend([
krbconf.setSection('domain_realm', dropts),
krbconf.emptyLine()
])
logger.debug("Writing Kerberos configuration to %s:", filename)
logger.debug("%s", krbconf.dump(opts))
krbconf.newConf(filename, opts)
# umask applies when creating a new file but we want 0o644 here
os.chmod(filename, 0o644)
def configure_certmonger(
fstore, subject_base, cli_realm, hostname, options, ca_enabled):
if not options.request_cert:
return
if not ca_enabled:
logger.warning("An RA is not configured on the server. "
"Not requesting host certificate.")
return
principal = 'host/%s@%s' % (hostname, cli_realm)
if options.hostname:
# If the hostname is explicitly set then we need to tell certmonger
# which principal name to use when requesting certs.
certmonger.add_principal_to_cas(principal)
cmonger = services.knownservices.certmonger
try:
cmonger.enable()
cmonger.start()
except Exception as e:
logger.error(
"Failed to configure automatic startup of the %s daemon: %s",
cmonger.service_name, str(e))
logger.warning(
"Automatic certificate management will not be available")
# Request our host cert
subject = str(DN(('CN', hostname), subject_base))
passwd_fname = os.path.join(paths.IPA_NSSDB_DIR, 'pwdfile.txt')
try:
certmonger.request_and_wait_for_cert(
certpath=paths.IPA_NSSDB_DIR,
storage='NSSDB',
nickname='Local IPA host',
subject=subject,
dns=[hostname],
principal=principal,
passwd_fname=passwd_fname,
resubmit_timeout=120,
)
except Exception as e:
logger.exception("certmonger request failed")
raise ScriptError(
"{} request for host certificate failed: {}".format(
cmonger.service_name, e
),
rval=CLIENT_INSTALL_ERROR
)
def configure_sssd_conf(
fstore, cli_realm, cli_domain, cli_server, options,
client_domain, client_hostname):
try:
sssdconfig = SSSDConfig.SSSDConfig()
sssdconfig.import_config()
except Exception as e:
if os.path.exists(paths.SSSD_CONF) and options.preserve_sssd:
# SSSD config is in place but we are unable to read it
# In addition, we are instructed to preserve it
# This all means we can't use it and have to bail out
logger.error(
"SSSD config exists but cannot be parsed: %s", str(e))
logger.error(
"Was instructed to preserve existing SSSD config")
logger.info(
"Correct errors in /etc/sssd/sssd.conf and re-run "
"installation")
return 1
# SSSD configuration does not exist or we are not asked to preserve it,
# create new one
# We do make new SSSDConfig instance because IPAChangeConf-derived
# classes have no means to reset their state and ParseError exception
# could come due to parsing error from older version which cannot be
# upgraded anymore, leaving sssdconfig instance practically unusable
# Note that we already backed up sssd.conf before going into this
# routine
if isinstance(e, IOError):
pass
else:
# It was not IOError so it must have been parsing error
logger.error(
"Unable to parse existing SSSD config. "
"As option --preserve-sssd was not specified, new config "
"will override the old one.")
logger.info(
"The old /etc/sssd/sssd.conf is backed up and "
"will be restored during uninstall.")
logger.info("New SSSD config will be created")
sssdconfig = SSSDConfig.SSSDConfig()
sssdconfig.new_config()
try:
domain = sssdconfig.new_domain(cli_domain)
except SSSDConfig.DomainAlreadyExistsError:
logger.info(
"Domain %s is already configured in existing SSSD "
"config, creating a new one.",
cli_domain)
logger.info(
"The old /etc/sssd/sssd.conf is backed up and will be restored "
"during uninstall.")
sssdconfig = SSSDConfig.SSSDConfig()
sssdconfig.new_config()
domain = sssdconfig.new_domain(cli_domain)
if options.on_master:
sssd_enable_service(sssdconfig, 'ifp')
if (
(options.conf_ssh and os.path.isfile(paths.SSH_CONFIG)) or
(options.conf_sshd and os.path.isfile(paths.SSHD_CONFIG))
):
try:
sssdconfig.new_service('ssh')
except SSSDConfig.ServiceAlreadyExists:
pass
except SSSDConfig.ServiceNotRecognizedError:
logger.error(
"Unable to activate the SSH service in SSSD config.")
logger.info(
"Please make sure you have SSSD built with SSH support "
"installed.")
logger.info(
"Configure SSH support manually in /etc/sssd/sssd.conf.")
sssdconfig.activate_service('ssh')
if options.conf_sudo:
# Activate the service in the SSSD config
try:
sssdconfig.new_service('sudo')
except SSSDConfig.ServiceAlreadyExists:
pass
except SSSDConfig.ServiceNotRecognizedError:
logger.error(
"Unable to activate the SUDO service in SSSD config.")
sssdconfig.activate_service('sudo')
configure_nsswitch_database(
fstore, 'sudoers', ['sss'],
default_value=['files'])
domain.add_provider('ipa', 'id')
# add discovery domain if client domain different from server domain
# do not set this config in server mode (#3947)
if not options.on_master and cli_domain != client_domain:
domain.set_option('dns_discovery_domain', cli_domain)
if not options.on_master:
if options.primary:
domain.set_option('ipa_server', ', '.join(cli_server))
else:
domain.set_option(
'ipa_server', '_srv_, %s' % ', '.join(cli_server))
else:
domain.set_option('ipa_server_mode', 'True')
# the master should only use itself for Kerberos
domain.set_option('ipa_server', cli_server[0])
# increase memcache timeout to 10 minutes when in server mode
try:
nss_service = sssdconfig.get_service('nss')
except SSSDConfig.NoServiceError:
nss_service = sssdconfig.new_service('nss')
nss_service.set_option('memcache_timeout', 600)
sssdconfig.save_service(nss_service)
domain.set_option('ipa_domain', cli_domain)
domain.set_option('ipa_hostname', client_hostname)
if cli_domain.lower() != cli_realm.lower():
domain.set_option('krb5_realm', cli_realm)
# Might need this if /bin/hostname doesn't return a FQDN
# domain.set_option('ipa_hostname', 'client.example.com')
domain.add_provider('ipa', 'auth')
domain.add_provider('ipa', 'chpass')
if not options.permit:
domain.add_provider('ipa', 'access')
else:
domain.add_provider('permit', 'access')
domain.set_option('cache_credentials', True)
# SSSD will need TLS for checking if ipaMigrationEnabled attribute is set
# Note that SSSD will force StartTLS because the channel is later used for
# authentication as well if password migration is enabled. Thus set
# the option unconditionally.
domain.set_option('ldap_tls_cacert', paths.IPA_CA_CRT)
if options.dns_updates:
domain.set_option('dyndns_update', True)
if options.all_ip_addresses:
domain.set_option('dyndns_iface', '*')
else:
iface = get_server_connection_interface(cli_server[0])
domain.set_option('dyndns_iface', iface)
if options.krb5_offline_passwords:
domain.set_option('krb5_store_password_if_offline', True)
domain.set_active(True)
sssdconfig.save_domain(domain)
sssdconfig.write(paths.SSSD_CONF)
return 0
def sssd_enable_service(sssdconfig, service):
try:
sssdconfig.new_service(service)
except SSSDConfig.ServiceAlreadyExists:
pass
except SSSDConfig.ServiceNotRecognizedError:
logger.error(
"Unable to activate the %s service in SSSD config.", service)
logger.info(
"Please make sure you have SSSD built with %s support "
"installed.", service)
logger.info(
"Configure %s support manually in /etc/sssd/sssd.conf.", service)
sssdconfig.activate_service(service)
def change_ssh_config(filename, changes, sections):
if not changes:
return True
try:
f = open(filename, 'r')
except IOError as e:
logger.error("Failed to open '%s': %s", filename, str(e))
return False
change_keys = tuple(key.lower() for key in changes)