# Authors: # Jason Gerard DeRose # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Test the `ipalib.crud` module. """ from ipatests.util import read_only, raises, get_api, ClassChecker from ipalib import crud, frontend, plugable, config from ipalib.parameters import Str class CrudChecker(ClassChecker): """ Class for testing base classes in `ipalib.crud`. """ def get_api(self, args=tuple(), options=tuple()): """ Return a finalized `ipalib.plugable.API` instance. """ (api, home) = get_api() class user(frontend.Object): takes_params = ( 'givenname', Str('sn', flags='no_update'), Str('uid', primary_key=True), 'initials', Str('uidnumber', flags=['no_create', 'no_search']) ) class user_verb(self.cls): takes_args = args takes_options = options api.register(user) api.register(user_verb) api.finalize() return api class test_Create(CrudChecker): """ Test the `ipalib.crud.Create` class. """ _cls = crud.Create def test_get_args(self): """ Test the `ipalib.crud.Create.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['uid'] assert api.Method.user_verb.args.uid.required is True def test_get_options(self): """ Test the `ipalib.crud.Create.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == \ ['givenname', 'sn', 'initials', 'all', 'raw', 'version'] for param in api.Method.user_verb.options(): if param.name != 'version': assert param.required is True api = self.get_api(options=('extra?',)) assert list(api.Method.user_verb.options) == \ ['givenname', 'sn', 'initials', 'extra', 'all', 'raw', 'version'] assert api.Method.user_verb.options.extra.required is False class test_Update(CrudChecker): """ Test the `ipalib.crud.Update` class. """ _cls = crud.Update def test_get_args(self): """ Test the `ipalib.crud.Update.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['uid'] assert api.Method.user_verb.args.uid.required is True def test_get_options(self): """ Test the `ipalib.crud.Update.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == \ ['givenname', 'initials', 'uidnumber', 'all', 'raw', 'version'] for param in api.Method.user_verb.options(): if param.name in ['all', 'raw']: assert param.required is True else: assert param.required is False class test_Retrieve(CrudChecker): """ Test the `ipalib.crud.Retrieve` class. """ _cls = crud.Retrieve def test_get_args(self): """ Test the `ipalib.crud.Retrieve.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['uid'] assert api.Method.user_verb.args.uid.required is True def test_get_options(self): """ Test the `ipalib.crud.Retrieve.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == ['all', 'raw', 'version'] class test_Delete(CrudChecker): """ Test the `ipalib.crud.Delete` class. """ _cls = crud.Delete def test_get_args(self): """ Test the `ipalib.crud.Delete.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['uid'] assert api.Method.user_verb.args.uid.required is True def test_get_options(self): """ Test the `ipalib.crud.Delete.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == ['version'] assert len(api.Method.user_verb.options) == 1 class test_Search(CrudChecker): """ Test the `ipalib.crud.Search` class. """ _cls = crud.Search def test_get_args(self): """ Test the `ipalib.crud.Search.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['criteria'] assert api.Method.user_verb.args.criteria.required is False def test_get_options(self): """ Test the `ipalib.crud.Search.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == \ ['givenname', 'sn', 'uid', 'initials', 'all', 'raw', 'version'] for param in api.Method.user_verb.options(): if param.name in ['all', 'raw']: assert param.required is True else: assert param.required is False class test_CrudBackend(ClassChecker): """ Test the `ipalib.crud.CrudBackend` class. """ _cls = crud.CrudBackend def get_subcls(self): class ldap(self.cls): pass return ldap def check_method(self, name, *args): o = self.cls() e = raises(NotImplementedError, getattr(o, name), *args) assert str(e) == 'CrudBackend.%s()' % name sub = self.subcls() e = raises(NotImplementedError, getattr(sub, name), *args) assert str(e) == 'ldap.%s()' % name def test_create(self): """ Test the `ipalib.crud.CrudBackend.create` method. """ self.check_method('create') def test_retrieve(self): """ Test the `ipalib.crud.CrudBackend.retrieve` method. """ self.check_method('retrieve', 'primary key', 'attribute') def test_update(self): """ Test the `ipalib.crud.CrudBackend.update` method. """ self.check_method('update', 'primary key') def test_delete(self): """ Test the `ipalib.crud.CrudBackend.delete` method. """ self.check_method('delete', 'primary key') def test_search(self): """ Test the `ipalib.crud.CrudBackend.search` method. """ self.check_method('search') > 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
# Authors: Karl MacMillan <kmacmillan@mentalrootkit.com>
#
# Copyright (C) 2007  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import time, logging

import os
import ldap
from ipaserver import ipaldap
from ldap import modlist
from ipalib import util
from ipalib import errors

DIRMAN_CN = "cn=directory manager"
CACERT = "/etc/ipa/ca.crt"
# the default container used by AD for user entries
WIN_USER_CONTAINER = "cn=Users"
# the default container used by IPA for user entries
IPA_USER_CONTAINER = "cn=users,cn=accounts"
PORT = 636
TIMEOUT = 120

IPA_REPLICA = 1
WINSYNC = 2

SASL_AUTH = ldap.sasl.sasl({}, 'GSSAPI')

def check_replication_plugin():
    """
    Confirm that the 389-ds replication is installed.

    Emit a message and return True/False
    """
    if not os.path.exists('/usr/lib/dirsrv/plugins/libreplication-plugin.so') and \
       not os.path.exists('/usr/lib64/dirsrv/plugins/libreplication-plugin.so'):
        print "The 389-ds replication plug-in was not found on this system"
        return False

    return True

class ReplicationManager:
    """Manage replication agreements between DS servers, and sync
    agreements with Windows servers"""
    def __init__(self, hostname, dirman_passwd):
        self.hostname = hostname
        self.dirman_passwd = dirman_passwd

        # If we are passed a password we'll use it as the DM password
        # otherwise we'll do a GSSAPI bind.
        self.conn = ipaldap.IPAdmin(hostname, port=PORT, cacert=CACERT)
        if dirman_passwd:
            self.conn.do_simple_bind(bindpw=dirman_passwd)
        else:
            self.conn.sasl_interactive_bind_s('', SASL_AUTH)

        self.repl_man_passwd = dirman_passwd

        # these are likely constant, but you could change them
        # at runtime if you really want
        self.repl_man_dn = "cn=replication manager,cn=config"
        self.repl_man_cn = "replication manager"
        self.suffix = ""

    def _get_replica_id(self, conn, master_conn):
        """
        Returns the replica ID which is unique for each backend.

        conn is the connection we are trying to get the replica ID for.
        master_conn is the master we are going to replicate with.
        """
        # First see if there is already one set
        dn = self.replica_dn()
        try:
            replica = conn.search_s(dn, ldap.SCOPE_BASE, "objectclass=*")[0]
            if replica.getValue('nsDS5ReplicaId'):
                return int(replica.getValue('nsDS5ReplicaId'))
        except ldap.NO_SUCH_OBJECT:
            pass

        # Ok, either the entry doesn't exist or the attribute isn't set
        # so get it from the other master
        retval = -1
        dn = "cn=replication, cn=etc, %s" % self.suffix
        try:
            replica = master_conn.search_s(dn, ldap.SCOPE_BASE, "objectclass=*")[0]
            if not replica.getValue('nsDS5ReplicaId'):
                logging.debug("Unable to retrieve nsDS5ReplicaId from remote server")
                raise RuntimeError("Unable to retrieve nsDS5ReplicaId from remote server")
        except ldap.NO_SUCH_OBJECT:
            logging.debug("Unable to retrieve nsDS5ReplicaId from remote server")
            raise

        # Now update the value on the master
        retval = int(replica.getValue('nsDS5ReplicaId'))
        mod = [(ldap.MOD_REPLACE, 'nsDS5ReplicaId', str(retval + 1))]

        try:
            master_conn.modify_s(dn, mod)
        except Exception, e:
            logging.debug("Problem updating nsDS5ReplicaID %s" % e)
            raise

        return retval

    def find_replication_dns(self, conn):
        """
        The replication agreements are stored in
        cn="$SUFFIX",cn=mapping tree,cn=config

        FIXME: Rather than failing with a read error if a user tries
        to read this it simply returns zero entries. We need to use
        GER to determine if we are allowed to read this to return a proper
        response. For now just return "No entries" even if the user may
        not be allowed to see them.
        """
        filt = "(|(objectclass=nsDSWindowsReplicationAgreement)(objectclass=nsds5ReplicationAgreement))"
        try:
            ents = conn.search_s("cn=mapping tree,cn=config", ldap.SCOPE_SUBTREE, filt)
        except ldap.NO_SUCH_OBJECT:
            return []
        return [ent.dn for ent in ents]

    def add_replication_manager(self, conn, passwd=None):
        """
        Create a pseudo user to use for replication. If no password
        is provided the directory manager password will be used.
        """

        if passwd:
            self.repl_man_passwd = passwd

        ent = ipaldap.Entry(self.repl_man_dn)
        ent.setValues("objectclass", "top", "person")
        ent.setValues("cn", self.repl_man_cn)
        ent.setValues("userpassword", self.repl_man_passwd)
        ent.setValues("sn", "replication manager pseudo user")

        try:
            conn.add_s(ent)
        except ldap.ALREADY_EXISTS:
            # should we set the password here?
            pass

    def delete_replication_manager(self, conn, dn="cn=replication manager,cn=config"):
        try:
            conn.delete_s(dn)
        except ldap.NO_SUCH_OBJECT:
            pass

    def get_replica_type(self, master=True):
        if master:
            return "3"
        else:
            return "2"

    def replica_dn(self):
        return 'cn=replica, cn="%s", cn=mapping tree, cn=config' % self.suffix

    def local_replica_config(self, conn, replica_id):
        dn = self.replica_dn()

        try:
            conn.getEntry(dn, ldap.SCOPE_BASE)
            # replication is already configured
            return
        except errors.NotFound:
            pass

        replica_type = self.get_replica_type()

        entry = ipaldap.Entry(dn)
        entry.setValues('objectclass', "top", "nsds5replica", "extensibleobject")
        entry.setValues('cn', "replica")
        entry.setValues('nsds5replicaroot', self.suffix)
        entry.setValues('nsds5replicaid', str(replica_id))
        entry.setValues('nsds5replicatype', replica_type)
        entry.setValues('nsds5flags', "1")
        entry.setValues('nsds5replicabinddn', [self.repl_man_dn])
        entry.setValues('nsds5replicalegacyconsumer', "off")

        conn.add_s(entry)

    def setup_changelog(self, conn):
        dn = "cn=changelog5, cn=config"
        dirpath = conn.dbdir + "/cldb"
        entry = ipaldap.Entry(dn)
        entry.setValues('objectclass', "top", "extensibleobject")
        entry.setValues('cn', "changelog5")
        entry.setValues('nsslapd-changelogdir', dirpath)
        try:
            conn.add_s(entry)
        except ldap.ALREADY_EXISTS:
            return

    def setup_chaining_backend(self, conn):
        chaindn = "cn=chaining database, cn=plugins, cn=config"