summaryrefslogtreecommitdiffstats
path: root/ipaserver/install/adtrust.py
blob: 2eddf453a291b9c7f535ca2caf910332fecc68b6 (plain)
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
#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#

"""
AD trust installer module
"""

from __future__ import print_function

import os

import six

from ipalib.constants import DOMAIN_LEVEL_0
from ipalib import errors
from ipaplatform.paths import paths
from ipapython.admintool import ScriptError
from ipapython import ipaldap, ipautil
from ipapython.dn import DN
from ipapython.ipa_log_manager import root_logger
from ipaserver.install import adtrustinstance
from ipaserver.install import service


if six.PY3:
    unicode = str

netbios_name = None
reset_netbios_name = False


def netbios_name_error(name):
    root_logger.error("\nIllegal NetBIOS name [%s].\n" % name)
    root_logger.error(
        "Up to 15 characters and only uppercase ASCII letters, digits "
        "and dashes are allowed. Empty string is not allowed.")


def read_netbios_name(netbios_default):
    netbios_name = ""

    print("Enter the NetBIOS name for the IPA domain.")
    print("Only up to 15 uppercase ASCII letters, digits "
          "and dashes are allowed.")
    print("Example: EXAMPLE.")
    print("")
    print("")
    if not netbios_default:
        netbios_default = "EXAMPLE"
    while True:
        netbios_name = ipautil.user_input(
            "NetBIOS domain name", netbios_default, allow_empty=False)
        print("")
        if adtrustinstance.check_netbios_name(netbios_name):
            break

        netbios_name_error(netbios_name)

    return netbios_name


def retrieve_netbios_name(api):
    flat_name_attr = 'ipantflatname'
    try:
        entry = api.Backend.ldap2.get_entry(
            DN(('cn', api.env.domain), api.env.container_cifsdomains,
               ipautil.realm_to_suffix(api.env.realm)),
            [flat_name_attr])
    except errors.NotFound:
        # trust not configured
        root_logger.debug("No previous trust configuration found")
        return None
    else:
        return entry.get(flat_name_attr)[0]


def set_and_check_netbios_name(netbios_name, unattended, api):
    """
    Depending if trust in already configured or not a given NetBIOS domain
    name must be handled differently.

    If trust is not configured the given NetBIOS is used or the NetBIOS is
    generated if none was given on the command line.

    If trust is  already configured the given NetBIOS name is used to reset
    the stored NetBIOS name it it differs from the current one.
    """

    cur_netbios_name = None
    gen_netbios_name = None
    reset_netbios_name = False
    entry = None

    if api.Backend.ldap2.isconnected():
        cur_netbios_name = retrieve_netbios_name(api)
    else:
        root_logger.debug(
            "LDAP is not connected, can not retrieve NetBIOS name")

    if cur_netbios_name and not netbios_name:
        # keep the current NetBIOS name
        netbios_name = cur_netbios_name
        reset_netbios_name = False
    elif cur_netbios_name and cur_netbios_name != netbios_name:
        # change the NetBIOS name
        print("Current NetBIOS domain name is %s, new name is %s.\n"
              % (cur_netbios_name, netbios_name))
        print("Please note that changing the NetBIOS name might "
              "break existing trust relationships.")
        if unattended:
            reset_netbios_name = True
            print("NetBIOS domain name will be changed to %s.\n"
                  % netbios_name)
        else:
            print("Say 'yes' if the NetBIOS shall be changed and "
                  "'no' if the old one shall be kept.")
            reset_netbios_name = ipautil.user_input(
                            'Do you want to reset the NetBIOS domain name?',
                            default=False, allow_empty=False)
        if not reset_netbios_name:
            netbios_name = cur_netbios_name
    elif cur_netbios_name and cur_netbios_name == netbios_name:
        # keep the current NetBIOS name
        reset_netbios_name = False
    elif not cur_netbios_name:
        if not netbios_name:
            gen_netbios_name = adtrustinstance.make_netbios_name(
                api.env.domain)

        if entry is not None:
            # Fix existing trust configuration
            print("Trust is configured but no NetBIOS domain name found, "
                  "setting it now.")
            reset_netbios_name = True
        else:
            # initial trust configuration
            reset_netbios_name = False
    else:
        # all possible cases should be covered above
        raise Exception('Unexpected state while checking NetBIOS domain name')

    if unattended and netbios_name is None and gen_netbios_name:
        netbios_name = gen_netbios_name

    if not adtrustinstance.check_netbios_name(netbios_name):
        if unattended:
            netbios_name_error(netbios_name)
            raise ScriptError("Aborting installation.")
        else:
            if netbios_name:
                netbios_name_error(netbios_name)
                netbios_name = None

    if not unattended and not netbios_name:
        netbios_name = read_netbios_name(gen_netbios_name)

    return (netbios_name, reset_netbios_name)


def enable_compat_tree():
    print("Do you want to enable support for trusted domains in Schema "
          "Compatibility plugin?")
    print("This will allow clients older than SSSD 1.9 and non-Linux "
          "clients to work with trusted users.")
    print("")
    enable_compat = ipautil.user_input(
        "Enable trusted domains support in slapi-nis?",
        default=False,
        allow_empty=False)
    print("")
    return enable_compat


def check_for_installed_deps():
    # Check if samba packages are installed
    if not adtrustinstance.check_inst():
        raise ScriptError("Aborting installation.")


def retrieve_entries_without_sid(api):
    """
    Retrieve a list of entries without assigned SIDs.
    :returns: a list of entries or an empty list if an error occurs
    """
    # The filter corresponds to ipa_sidgen_task.c LDAP search filter
    filter = '(&(objectclass=ipaobject)(!(objectclass=mepmanagedentry))' \
             '(|(objectclass=posixaccount)(objectclass=posixgroup)' \
             '(objectclass=ipaidobject))(!(ipantsecurityidentifier=*)))'
    base_dn = api.env.basedn
    try:
        root_logger.debug(
            "Searching for objects with missing SID with "
            "filter=%s, base_dn=%s", filter, base_dn)
        entries, _truncated = api.Backend.ldap2.find_entries(
            filter=filter, base_dn=base_dn, attrs_list=[''])
        return entries
    except errors.NotFound:
        # All objects have SIDs assigned
        pass
    except (errors.DatabaseError, errors.NetworkError) as e:
        root_logger.error(
            "Could not retrieve a list of objects that need a SID "
            "identifier assigned: %s", e)

    return []


def retrieve_and_ask_about_sids(api, options):
    entries = []
    if api.Backend.ldap2.isconnected():
        entries = retrieve_entries_without_sid(api)
    else:
        root_logger.debug(
            "LDAP backend not connected, can not retrieve entries "
            "with missing SID")

    object_count = len(entries)
    if object_count > 0:
        print("")
        print("WARNING: %d existing users or groups do not have "
              "a SID identifier assigned." % len(entries))
        print("Installer can run a task to have ipa-sidgen "
              "Directory Server plugin generate")
        print("the SID identifier for all these users. Please note, "
              "the in case of a high")
        print("number of users and groups, the operation might "
              "lead to high replication")
        print("traffic and performance degradation. Refer to "
              "ipa-adtrust-install(1) man page")
        print("for details.")
        print("")
        if options.unattended:
            print("Unattended mode was selected, installer will "
                  "NOT run ipa-sidgen task!")
        else:
            if ipautil.user_input(
                    "Do you want to run the ipa-sidgen task?",
                    default=False,
                    allow_empty=False):
                options.add_sids = True


def retrieve_potential_adtrust_agents(api):
    """
    Retrieve a sorted list of potential AD trust agents

    :param api: initialized API instance
    :returns: sorted list of FQDNs of masters which are not AD trust agents
    """
    try:
        # Search only masters which have support for domain levels
        # because only these masters will have SSSD recent enough
        # to support AD trust agents
        dl_enabled_masters = api.Command.server_find(
            ipamindomainlevel=DOMAIN_LEVEL_0, all=True)['result']
    except (errors.DatabaseError, errors.NetworkError) as e:
        root_logger.error(
            "Could not retrieve a list of existing IPA masters: %s", e)
        return

    try:
        # search for existing AD trust agents
        adtrust_agents = api.Command.server_find(
            servrole=u'AD trust agent', all=True)['result']
    except (errors.DatabaseError, errors.NetworkError) as e:
        root_logger.error("Could not retrieve a list of adtrust agents: %s", e)
        return

    dl_enabled_master_cns = {m['cn'][0] for m in dl_enabled_masters}
    adtrust_agents_cns = {m['cn'][0] for m in adtrust_agents}

    potential_agents_cns = dl_enabled_master_cns - adtrust_agents_cns

    # remove the local host from the potential agents since it will be set up
    # by adtrustinstance configuration code
    potential_agents_cns -= {api.env.host}
    return sorted(potential_agents_cns)


def add_hosts_to_adtrust_agents(api, host_list):
    """
    Add the CIFS and host principals to the 'adtrust agents'
    group as 389-ds only operates with GroupOfNames, we have to
    use the principal's proper dn as defined in self.cifs_agent

    :param api: API instance
    :param host_list: list of potential AD trust agent FQDNs
    """
    agents_dn = DN(
        ('cn', 'adtrust agents'), ('cn', 'sysaccounts'),
        ('cn', 'etc'), api.env.basedn)

    service.add_principals_to_group(
        api.Backend.ldap2,
        agents_dn,
        "member",
        [api.Object.host.get_dn(x) for x in host_list])


def add_new_adtrust_agents(api, options):
    """
    Find out IPA masters which are not part of the cn=adtrust agents
    and propose them to be added to the list
    :param api: API instance
    :param options: parsed CLI options
    """
    potential_agents_cns = retrieve_potential_adtrust_agents(api)

    if potential_agents_cns:
        print("")
        print("WARNING: %d IPA masters are not yet able to serve "
              "information about users from trusted forests."
              % len(potential_agents_cns))
        print("Installer can add them to the list of IPA masters "
              "allowed to access information about trusts.")
        print("If you choose to do so, you also need to restart "
              "LDAP service on those masters.")
        print("Refer to ipa-adtrust-install(1) man page for details.")
        print("")
        if options.unattended:
            print("Unattended mode was selected, installer will NOT "
                  "add other IPA masters to the list of allowed to")
            print("access information about trusted forests!")
            return

    new_agents = []

    for name in sorted(potential_agents_cns):
        if ipautil.user_input(
                "IPA master [%s]?" % (name),
                default=False,
                allow_empty=False):
            new_agents.append(name)

    if new_agents:
        add_hosts_to_adtrust_agents(api, new_agents)

        print("""
WARNING: you MUST restart (e.g. ipactl restart) the following IPA masters in
order to activate them to serve information about users from trusted forests:
""")
        for x in new_agents:
            print(x)


def install_check(standalone, options, api):
    global netbios_name
    global reset_netbios_name

    if standalone:
        check_for_installed_deps()

    realm_not_matching_domain = (api.env.domain.upper() != api.env.realm)

    if realm_not_matching_domain:
        print("WARNING: Realm name does not match the domain name.\n"
              "You will not be able to estabilish trusts with Active "
              "Directory unless\nthe realm name of the IPA server matches its "
              "domain name.\n\n")
        if not options.unattended:
            if not ipautil.user_input("Do you wish to continue?",
                                      default=False,
                                      allow_empty=False):
                raise ScriptError("Aborting installation.")

    # Check if /etc/samba/smb.conf already exists. In case it was not generated
    # by IPA, print a warning that we will break existing configuration.

    if adtrustinstance.ipa_smb_conf_exists():
        if not options.unattended:
            print("IPA generated smb.conf detected.")
            if not ipautil.user_input("Overwrite smb.conf?",
                                      default=False,
                                      allow_empty=False):
                raise ScriptError("Aborting installation.")

    elif os.path.exists(paths.SMB_CONF):
        print("WARNING: The smb.conf already exists. Running "
              "ipa-adtrust-install will break your existing samba "
              "configuration.\n\n")
        if not options.unattended:
            if not ipautil.user_input("Do you wish to continue?",
                                      default=False,
                                      allow_empty=False):
                raise ScriptError("Aborting installation.")
    elif os.path.exists(paths.SMB_CONF):
        print("WARNING: The smb.conf already exists. Running "
              "ipa-adtrust-install will break your existing samba "
              "configuration.\n\n")
        if not options.unattended:
            if not ipautil.user_input("Do you wish to continue?",
                                      default=False,
                                      allow_empty=False):
                raise ScriptError("Aborting installation.")

    if not options.unattended and not options.enable_compat:
        options.enable_compat = enable_compat_tree()

    netbios_name, reset_netbios_name = set_and_check_netbios_name(
        options.netbios_name, options.unattended, api)

    if not options.add_sids:
        retrieve_and_ask_about_sids(api, options)


def install(standalone, options, fstore, api):
    if not options.unattended and standalone:
        print("")
        print("The following operations may take some minutes to complete.")
        print("Please wait until the prompt is returned.")
        print("")

    smb = adtrustinstance.ADTRUSTInstance(fstore)
    smb.realm = api.env.realm
    smb.autobind = ipaldap.AUTOBIND_ENABLED
    smb.setup(api.env.host, api.env.realm,
              netbios_name, reset_netbios_name,
              options.rid_base, options.secondary_rid_base,
              options.add_sids,
              enable_compat=options.enable_compat)
    smb.find_local_id_range()
    smb.create_instance()

    if options.add_agents:
        # Find out IPA masters which are not part of the cn=adtrust agents
        # and propose them to be added to the list
        add_new_adtrust_agents(api, options)