Exemplo n.º 1
0
def samdb_connect(ctx):
    '''make a ldap connection to the server'''
    try:
        ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
                          session_info=system_session(),
                          credentials=ctx.creds,
                          lp=ctx.lp)
    except Exception as e:
        raise CommandError("LDAP connection to %s failed" % ctx.server, e)
Exemplo n.º 2
0
def get_partition(samdb, part):
    # Allow people to say "--partition=DOMAIN" rather than
    # "--partition=DC=blah,DC=..."
    if part is not None:
        short_partitions, long_partitions = get_partition_maps(samdb)
        part = short_partitions.get(part.upper(), part)
        if part not in long_partitions:
            raise CommandError("unknown partition %s" % part)
    return part
Exemplo n.º 3
0
 def run(self, file, use_ntvfs=False, use_s3fs=False,
         as_sddl=False, xattr_backend=None, eadb_file=None,
         credopts=None, sambaopts=None, versionopts=None):
     lp = sambaopts.get_loadparm()
     try:
         samdb = SamDB(session_info=system_session(),
                       lp=lp)
     except Exception, e:
         raise CommandError("Unable to open samdb:", e)
Exemplo n.º 4
0
    def drsuapi_ReplicaInfo(ctx, info_type):
        '''call a DsReplicaInfo'''

        req1 = drsuapi.DsReplicaGetInfoRequest1()
        req1.info_type = info_type
        try:
            (info_type, info) = ctx.drsuapi.DsReplicaGetInfo(ctx.drsuapi_handle, 1, req1)
        except Exception, e:
            raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
Exemplo n.º 5
0
    def run(self, ou_dn, credopts=None, sambaopts=None, versionopts=None,
            H=None, description=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        samdb = SamDB(url=H, session_info=system_session(),
                      credentials=creds, lp=lp)

        try:
            full_ou_dn = samdb.normalize_dn_in_domain(ou_dn)
        except Exception as e:
            raise CommandError('Invalid ou_dn "%s": %s' % (ou_dn, e))

        try:
            samdb.create_ou(full_ou_dn, description=description)
        except Exception as e:
            raise CommandError('Failed to add ou "%s"' % full_ou_dn, e)

        self.outf.write('Added ou "%s"\n' % full_ou_dn)
Exemplo n.º 6
0
Arquivo: ou.py Projeto: iboukris/samba
class cmd_delete(Command):
    """Delete an organizational unit.

    The name of the organizational unit can be specified as a full DN
    or without the domainDN component.

    Examples:
    samba-tool ou delete 'OU=OrgUnit,DC=samdom,DC=example,DC=com'
    samba-tool ou delete 'OU=OrgUnit'

    The examples show how an administrator would delete the ou 'OrgUnit'.
    """

    synopsis = "%prog <ou_dn> [options]"

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server",
               type=str, metavar="URL", dest="H"),
        Option("--force-subtree-delete", dest="force_subtree_delete",
               default=False, action='store_true',
               help="Delete organizational unit and all children reclusively"),
    ]

    takes_args = ["ou_dn"]
    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "versionopts": options.VersionOptions,
        }

    def run(self, ou_dn, credopts=None, sambaopts=None, versionopts=None,
            H=None, force_subtree_delete=False):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        samdb = SamDB(url=H, session_info=system_session(),
                      credentials=creds, lp=lp)
        domain_dn = ldb.Dn(samdb, samdb.domain_dn())

        try:
            full_ou_dn = samdb.normalize_dn_in_domain(ou_dn)
        except Exception, e:
            raise CommandError('Invalid ou_dn "%s": %s' % (ou_dn, e.message))

        controls = []
        if force_subtree_delete:
            controls = ["tree_delete:1"]

        try:
            res = samdb.search(base=full_ou_dn,
                               expression="(objectclass=organizationalUnit)",
                               scope=ldb.SCOPE_BASE, attrs=[])
            if len(res) == 0:
                self.outf.write('Unable to find ou "%s"\n' % ou_dn)
                return
            samdb.delete(full_ou_dn, controls)
        except Exception, e:
            raise CommandError('Failed to delete ou "%s"' % full_ou_dn, e)
Exemplo n.º 7
0
def check_pso_constraints(min_pwd_length=None, history_length=None,
                          min_pwd_age=None, max_pwd_age=None):
    """Checks PSO settings fall within valid ranges"""

    # check values as per section 3.1.1.5.2.2 Constraints in MS-ADTS spec
    if history_length is not None and history_length > 1024:
        raise CommandError("Bad password history length: "
                           "valid range is 0 to 1024")

    if min_pwd_length is not None and min_pwd_length > 255:
        raise CommandError("Bad minimum password length: "
                           "valid range is 0 to 255")

    if min_pwd_age is not None and max_pwd_age is not None:
        # note max-age=zero is a special case meaning 'never expire'
        if min_pwd_age >= max_pwd_age and max_pwd_age != 0:
            raise CommandError("Minimum password age must be less than "
                               "maximum age")
Exemplo n.º 8
0
    def run(self,
            groupname,
            listofmembers=None,
            credopts=None,
            sambaopts=None,
            versionopts=None,
            H=None,
            member_base_dn=None,
            member_dn=None,
            object_types="user,group,computer"):

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)

        if member_dn is None and listofmembers is None:
            self.usage()
            raise CommandError(
                'Either listofmembers or --member-dn must be specified.')

        try:
            samdb = SamDB(url=H,
                          session_info=system_session(),
                          credentials=creds,
                          lp=lp)
            groupmembers = []
            if member_dn is not None:
                groupmembers += member_dn
            if listofmembers is not None:
                groupmembers += listofmembers.split(',')
            group_member_types = object_types.split(',')

            if member_base_dn is not None:
                member_base_dn = samdb.normalize_dn_in_domain(member_base_dn)

            samdb.add_remove_group_members(groupname,
                                           groupmembers,
                                           add_members_operation=True,
                                           member_types=group_member_types,
                                           member_base_dn=member_base_dn)
        except Exception as e:
            # FIXME: catch more specific exception
            raise CommandError('Failed to add members %r to group "%s" - %s' %
                               (groupmembers, groupname, e))
        self.outf.write("Added members to group %s\n" % groupname)
Exemplo n.º 9
0
    def run(self,
            accountname,
            onoff,
            H=None,
            credopts=None,
            sambaopts=None,
            versionopts=None):

        on = False
        if onoff == "on":
            on = True
        elif onoff == "off":
            on = False
        else:
            raise CommandError(
                "invalid argument: '%s' (choose from 'on', 'off')" % onoff)

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        if H == None:
            path = paths.samdb
        else:
            path = H

        sam = SamDB(path,
                    session_info=system_session(),
                    credentials=creds,
                    lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname)

        search_filter = "sAMAccountName=%s" % ldb.binary_encode(cleanedaccount)
        flag = dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
        try:
            sam.toggle_userAccountFlags(
                search_filter,
                flag,
                flags_str="Trusted-to-Authenticate-for-Delegation",
                on=on,
                strict=True)
        except Exception, err:
            raise CommandError(err)
Exemplo n.º 10
0
    def run(self, server, zone, name, rtype, olddata, newdata,
            sambaopts=None, credopts=None, versionopts=None):

        if rtype.upper() not in ('A', 'AAAA', 'PTR', 'CNAME', 'NS', 'MX', 'SOA', 'SRV', 'TXT'):
            raise CommandError('Updating record of type %s is not supported' % rtype)

        record_type = dns_type_flag(rtype)
        rec = data_to_dns_record(record_type, newdata)

        self.lp = sambaopts.get_loadparm()
        self.creds = credopts.get_credentials(self.lp)
        dns_conn = dns_connect(server, self.lp, self.creds)

        rec_match = dns_record_match(dns_conn, server, zone, name, record_type,
                                     olddata)
        if not rec_match:
            raise CommandError('Record or zone does not exist.')

        # Copy properties from existing record to new record
        rec.dwFlags = rec_match.dwFlags
        rec.dwSerial = rec_match.dwSerial
        rec.dwTtlSeconds = rec_match.dwTtlSeconds
        rec.dwTimeStamp = rec_match.dwTimeStamp

        add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
        add_rec_buf.rec = rec

        del_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
        del_rec_buf.rec = rec_match

        try:
            dns_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
                                         0,
                                         server,
                                         zone,
                                         name,
                                         add_rec_buf,
                                         del_rec_buf)
        except WERRORError as e:
            if e.args[0] == werror.WERR_DNS_ERROR_NAME_DOES_NOT_EXIST:
                self.outf.write('Zone does not exist; record could not be updated.\n')
            raise e

        self.outf.write('Record updated successfully\n')
Exemplo n.º 11
0
    def run(self, sambaopts, versionopts, section_name=None,
            parameter_name=None, client_ip=None, client_name=None,
            verbose=False, suppress_prompt=None, show_all_parameters=False,
            server=None):
        if server:
            raise NotImplementedError("--server not yet implemented")
        if show_all_parameters:
            raise NotImplementedError("--show-all-parameters not yet implemented")
        if client_name is not None and client_ip is None:
            raise CommandError("Both a DNS name and an IP address are "
                               "required for the host access check")

        try:
            lp = sambaopts.get_loadparm()
        except RuntimeError as err:
            raise CommandError(err)

        # We need this to force the output
        samba.set_debug_level(2)

        logger = self.get_logger("testparm")

        logger.info("Loaded smb config files from %s", lp.configfile)
        logger.info("Loaded services file OK.")

        valid = self.do_global_checks(lp, logger)
        valid = valid and self.do_share_checks(lp, logger)
        if client_name is not None and client_ip is not None:
            self.check_client_access(lp, logger, client_name, client_ip)
        else:
            if section_name is not None or parameter_name is not None:
                if parameter_name is None:
                    lp[section_name].dump(verbose)
                else:
                    lp.dump_a_parameter(parameter_name, section_name)
            else:
                if not suppress_prompt:
                    self.outf.write("Press enter to see a dump of your service definitions\n")
                    sys.stdin.readline()
                lp.dump(verbose)
        if valid:
            return
        else:
            raise CommandError("Invalid smb.conf")
Exemplo n.º 12
0
    def seize_role(self, role, samdb, force):
        res = samdb.search("",
                           scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
        assert len(res) == 1
        serviceName = res[0]["dsServiceName"][0]
        domain_dn = samdb.domain_dn()
        self.infrastructure_dn = "CN=Infrastructure," + domain_dn
        self.naming_dn = "CN=Partitions,%s" % samdb.get_config_basedn()
        self.schema_dn = str(samdb.get_schema_basedn())
        self.rid_dn = "CN=RID Manager$,CN=System," + domain_dn

        m = ldb.Message()
        if role == "rid":
            m.dn = ldb.Dn(samdb, self.rid_dn)
        elif role == "pdc":
            m.dn = ldb.Dn(samdb, domain_dn)
        elif role == "naming":
            m.dn = ldb.Dn(samdb, self.naming_dn)
        elif role == "infrastructure":
            m.dn = ldb.Dn(samdb, self.infrastructure_dn)
        elif role == "schema":
            m.dn = ldb.Dn(samdb, self.schema_dn)
        else:
            raise CommandError("Invalid FSMO role.")
        #first try to transfer to avoid problem if the owner is still active
        if force is None:
            self.message("Attempting transfer...")
            try:
                transfer_role(self.outf, role, samdb)
                self.outf.write("FSMO seize was not required, as transfer of '%s' role was successful\n" % role)
                return
            except CommandError:
            #transfer failed, use the big axe...
                self.message("Transfer unsuccessful, seizing...")
        else:
            self.message("Will not attempt transfer, seizing...")

        m["fSMORoleOwner"]= ldb.MessageElement(
            serviceName, ldb.FLAG_MOD_REPLACE,
            "fSMORoleOwner")
        try:
            samdb.modify(m)
        except LdbError, (num, msg):
            raise CommandError("Failed to initiate role seize of '%s' role: %s" % (role, msg))
Exemplo n.º 13
0
def get_gpo_containers(samdb, gpo):
    '''lists dn of containers for a GPO'''

    search_expr = "(&(objectClass=*)(gPLink=*%s*))" % gpo
    try:
        msg = samdb.search(expression=search_expr, attrs=['gPLink'])
    except Exception as e:
        raise CommandError("Could not find container(s) with GPO %s" % gpo, e)

    return msg
Exemplo n.º 14
0
def get_fsmo_roleowner(samdb, roledn):
    """Gets the owner of an FSMO role

    :param roledn: The DN of the FSMO role
    """
    res = samdb.search(roledn, scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
    if len(res) == 0:
        raise CommandError('"%s" does not have a FSMO roleowner' % roledn)
    master_owner = res[0]["fSMORoleOwner"][0]
    return master_owner
Exemplo n.º 15
0
Arquivo: spn.py Projeto: szaydel/samba
    def run(self, name, user, H=None,
            credopts=None,
            sambaopts=None,
            versionopts=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        sam = SamDB(H, session_info=system_session(),
                    credentials=creds, lp=lp)
        res = sam.search(
            expression="servicePrincipalName=%s" % ldb.binary_encode(name),
            scope=ldb.SCOPE_SUBTREE)
        if len(res) != 0:
            raise CommandError("Service principal %s already"
                               " affected to another user" % name)

        (cleaneduser, realm, domain) = _get_user_realm_domain(user)
        res = sam.search(
            expression="samaccountname=%s" % ldb.binary_encode(cleaneduser),
            scope=ldb.SCOPE_SUBTREE, attrs=["servicePrincipalName"])
        if len(res) > 0:
            res[0].dn
            msg = ldb.Message()
            spns = res[0].get("servicePrincipalName")
            tab = []
            found = False
            flag = ldb.FLAG_MOD_ADD
            if spns is not None:
                for e in spns:
                    if str(e) == name:
                        found = True
                    tab.append(str(e))
                flag = ldb.FLAG_MOD_REPLACE
            tab.append(name)
            msg.dn = res[0].dn
            msg["servicePrincipalName"] = ldb.MessageElement(tab, flag,
                                                             "servicePrincipalName")
            if not found:
                sam.modify(msg)
            else:
                raise CommandError("Service principal %s already"
                                   " affected to %s" % (name, user))
        else:
            raise CommandError("User %s not found" % user)
Exemplo n.º 16
0
Arquivo: gpo.py Projeto: lausser/samba
def del_gpo_link(samdb, container_dn, gpo):
    '''delete GPO link for the container'''
    # Check if valid Container DN and get existing GPlinks
    try:
        msg = samdb.search(base=container_dn,
                           scope=ldb.SCOPE_BASE,
                           expression="(objectClass=*)",
                           attrs=['gPLink'])[0]
    except Exception, e:
        raise CommandError("Container '%s' does not exist" % container_dn, e)
Exemplo n.º 17
0
    def seize_dns_role(self, role, samdb, credopts, sambaopts, versionopts,
                       force):
        """Seize DNS FSMO role. """

        serviceName = samdb.get_dsServiceName()
        domain_dn = samdb.domain_dn()
        forest_dn = samba.dn_from_dns_name(samdb.forest_dns_name())
        self.domaindns_dn = "CN=Infrastructure,DC=DomainDnsZones," + domain_dn
        self.forestdns_dn = "CN=Infrastructure,DC=ForestDnsZones," + forest_dn

        m = ldb.Message()
        if role == "domaindns":
            m.dn = ldb.Dn(samdb, self.domaindns_dn)
        elif role == "forestdns":
            m.dn = ldb.Dn(samdb, self.forestdns_dn)
        else:
            raise CommandError("Invalid FSMO role.")
        #first try to transfer to avoid problem if the owner is still active
        seize = False
        master_owner = get_fsmo_roleowner(samdb, m.dn)
        if master_owner != serviceName:
            if force is None:
                self.message("Attempting transfer...")
                if not transfer_dns_role(self.outf, sambaopts, credopts, role,
                                         samdb):
                    #transfer failed, use the big axe...
                    seize = True
                    self.message("Transfer unsuccessful, seizing...")
                else:
                    self.message(
                        "Not seizing role as transfer was successful\n")

            if force is not None or seize == True:
                self.message("Seizing %s FSMO role..." % role)
                m["fSMORoleOwner"] = ldb.MessageElement(
                    serviceName, ldb.FLAG_MOD_REPLACE, "fSMORoleOwner")
                try:
                    samdb.modify(m)
                except LdbError, (num, msg):
                    raise CommandError("Failed to seize '%s' role: %s" %
                                       (role, msg))
                self.outf.write("FSMO seize of '%s' role successful\n" % role)
                return True
Exemplo n.º 18
0
    def run(self,
            computername,
            new_ou_dn,
            credopts=None,
            sambaopts=None,
            versionopts=None,
            H=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        samdb = SamDB(url=H,
                      session_info=system_session(),
                      credentials=creds,
                      lp=lp)
        domain_dn = ldb.Dn(samdb, samdb.domain_dn())

        samaccountname = computername
        if not computername.endswith('$'):
            samaccountname = "%s$" % computername

        filter = (
            "(&(sAMAccountName=%s)(sAMAccountType=%u))" %
            (ldb.binary_encode(samaccountname), dsdb.ATYPE_WORKSTATION_TRUST))
        try:
            res = samdb.search(base=domain_dn,
                               expression=filter,
                               scope=ldb.SCOPE_SUBTREE)
            computer_dn = res[0].dn
        except IndexError:
            raise CommandError('Unable to find computer "%s"' % (computername))

        full_new_ou_dn = ldb.Dn(samdb, new_ou_dn)
        if not full_new_ou_dn.is_child_of(domain_dn):
            full_new_ou_dn.add_base(domain_dn)
        new_computer_dn = ldb.Dn(samdb, str(computer_dn))
        new_computer_dn.remove_base_components(len(computer_dn) - 1)
        new_computer_dn.add_base(full_new_ou_dn)
        try:
            samdb.rename(computer_dn, new_computer_dn)
        except Exception as e:
            raise CommandError('Failed to move computer "%s"' % computername,
                               e)
        self.outf.write('Moved computer "%s" to "%s"\n' %
                        (computername, new_ou_dn))
Exemplo n.º 19
0
Arquivo: ou.py Projeto: zhoury14/samba
    def run(self,
            old_ou_dn,
            new_parent_dn,
            credopts=None,
            sambaopts=None,
            versionopts=None,
            H=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        samdb = SamDB(url=H,
                      session_info=system_session(),
                      credentials=creds,
                      lp=lp)

        domain_dn = ldb.Dn(samdb, samdb.domain_dn())
        try:
            full_old_ou_dn = samdb.normalize_dn_in_domain(old_ou_dn)
        except Exception as e:
            raise CommandError('Invalid old_ou_dn "%s": %s' %
                               (old_ou_dn, e.message))
        try:
            full_new_parent_dn = samdb.normalize_dn_in_domain(new_parent_dn)
        except Exception as e:
            raise CommandError('Invalid new_parent_dn "%s": %s' %
                               (new_parent_dn, e.message))

        full_new_ou_dn = ldb.Dn(samdb, str(full_old_ou_dn))
        full_new_ou_dn.remove_base_components(len(full_old_ou_dn) - 1)
        full_new_ou_dn.add_base(full_new_parent_dn)

        try:
            res = samdb.search(base=full_old_ou_dn,
                               expression="(objectclass=organizationalUnit)",
                               scope=ldb.SCOPE_BASE,
                               attrs=[])
            if len(res) == 0:
                self.outf.write('Unable to find ou "%s"\n' % full_old_ou_dn)
                return
            samdb.rename(full_old_ou_dn, full_new_ou_dn)
        except Exception as e:
            raise CommandError('Failed to move ou "%s"' % full_old_ou_dn, e)
        self.outf.write('Moved ou "%s" into "%s"\n' %
                        (full_old_ou_dn, full_new_parent_dn))
Exemplo n.º 20
0
def dns_connect(server, lp, creds):
    if server.lower() == 'localhost':
        server = '127.0.0.1'
    binding_str = "ncacn_ip_tcp:%s[sign]" % server
    try:
        dns_conn = dnsserver.dnsserver(binding_str, lp, creds)
    except RuntimeError as e:
        raise CommandError('Connecting to DNS RPC server %s failed with %s' % (server, e))

    return dns_conn
Exemplo n.º 21
0
def get_sid_for_restore(samdb):
    # Find the DN of the RID set of the server
    res = samdb.search(base=ldb.Dn(samdb, samdb.get_serverName()),
                       scope=ldb.SCOPE_BASE,
                       attrs=["serverReference"])
    server_ref_dn = ldb.Dn(samdb, res[0]['serverReference'][0])
    res = samdb.search(base=server_ref_dn,
                       scope=ldb.SCOPE_BASE,
                       attrs=['rIDSetReferences'])
    rid_set_dn = ldb.Dn(samdb, res[0]['rIDSetReferences'][0])

    # Get the alloc pools and next RID of the RID set
    res = samdb.search(
        base=rid_set_dn,
        scope=ldb.SCOPE_SUBTREE,
        expression="(rIDNextRID=*)",
        attrs=['rIDAllocationPool', 'rIDPreviousAllocationPool', 'rIDNextRID'])

    # Decode the bounds of the RID allocation pools
    rid = int(res[0].get('rIDNextRID')[0])

    def split_val(num):
        high = (0xFFFFFFFF00000000 & int(num)) >> 32
        low = 0x00000000FFFFFFFF & int(num)
        return low, high

    pool_l, pool_h = split_val(res[0].get('rIDPreviousAllocationPool')[0])
    npool_l, npool_h = split_val(res[0].get('rIDAllocationPool')[0])

    # Calculate next RID based on pool bounds
    if rid == npool_h:
        raise CommandError('Out of RIDs, finished AllocPool')
    if rid == pool_h:
        if pool_h == npool_h:
            raise CommandError('Out of RIDs, finished PrevAllocPool.')
        rid = npool_l
    else:
        rid += 1

    # Construct full SID
    sid = dom_sid(samdb.get_domain_sid())
    return str(sid) + '-' + str(rid)
Exemplo n.º 22
0
    def run(self, attribute, H=None, credopts=None, sambaopts=None,
            versionopts=None, searchflags=None):

        if searchflags is None:
            raise CommandError('A value to modify must be provided.')

        # Parse the search flags to a set of bits to modify.

        searchflags_int = None
        if searchflags is not None:
            searchflags_int = 0
            flags = searchflags.split(',')
            # We have to normalise all the values. To achieve this predictably
            # we title case (Fattrindex), then swapcase (fATTINDEX)
            flags = [ x.capitalize().swapcase() for x in flags ]
            for flag in flags:
                if flag not in bitFields['searchflags'].keys():
                    raise CommandError("Unknown flag '%s', please see --help" % flag)
                bit_loc = 31 - bitFields['searchflags'][flag]
                # Now apply the bit.
                searchflags_int = searchflags_int | (1 << bit_loc)

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)

        samdb = SamDB(url=H, session_info=system_session(),
            credentials=creds, lp=lp)

        schema_dn = samdb.schema_dn()
        # For now we make assumptions about the CN
        attr_dn = 'cn=%s,%s' % (attribute, schema_dn)

        m = ldb.Message()
        m.dn = ldb.Dn(samdb, attr_dn)

        if searchflags_int is not None:
            m['searchFlags'] = ldb.MessageElement(
                str(searchflags_int), ldb.FLAG_MOD_REPLACE, 'searchFlags')

        samdb.modify(m)
        samdb.set_schema_update_now()
        self.outf.write("modified %s" % attr_dn)
Exemplo n.º 23
0
    def run(self,
            file,
            use_ntvfs=False,
            use_s3fs=False,
            as_sddl=False,
            xattr_backend=None,
            eadb_file=None,
            credopts=None,
            sambaopts=None,
            versionopts=None,
            service=None):
        lp = sambaopts.get_loadparm()
        try:
            samdb = SamDB(session_info=system_session(), lp=lp)
        except Exception as e:
            raise CommandError("Unable to open samdb:", e)

        if not use_ntvfs and not use_s3fs:
            use_ntvfs = "smb" in lp.get("server services")
        elif use_s3fs:
            use_ntvfs = False

        s3conf = s3param.get_context()
        s3conf.load(lp.configfile)
        # ensure we are using the right samba_dsdb passdb backend, no matter what
        s3conf.set("passdb backend", "samba_dsdb:%s" % samdb.url)

        acl = getntacl(lp,
                       file,
                       xattr_backend,
                       eadb_file,
                       direct_db_access=use_ntvfs,
                       service=service)
        if as_sddl:
            try:
                domain_sid = security.dom_sid(samdb.domain_sid)
            except:
                raise CommandError(
                    "Unable to read domain SID from configuration files")
            self.outf.write(acl.as_sddl(domain_sid) + "\n")
        else:
            self.outf.write(ndr_print(acl))
Exemplo n.º 24
0
def dns_client_version(cli_version):
    version = cli_version.upper()
    if version == 'W2K':
        client_version = dnsserver.DNS_CLIENT_VERSION_W2K
    elif version == 'DOTNET':
        client_version = dnsserver.DNS_CLIENT_VERSION_DOTNET
    elif version == 'LONGHORN':
        client_version = dnsserver.DNS_CLIENT_VERSION_LONGHORN
    else:
        raise CommandError('Unknown client version %s' % cli_version)
    return client_version
Exemplo n.º 25
0
    def run(self,
            groupname,
            credopts=None,
            sambaopts=None,
            versionopts=None,
            H=None,
            full_dn=False):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)

        try:
            samdb = SamDB(url=H,
                          session_info=system_session(),
                          credentials=creds,
                          lp=lp)

            search_filter = "(&(objectClass=group)(samaccountname=%s))" % groupname
            res = samdb.search(samdb.domain_dn(),
                               scope=ldb.SCOPE_SUBTREE,
                               expression=(search_filter),
                               attrs=["objectSid"])

            if (len(res) != 1):
                return

            group_dn = res[0].get('dn', idx=0)
            object_sid = res[0].get('objectSid', idx=0)

            object_sid = ndr_unpack(security.dom_sid, object_sid)
            (group_dom_sid, rid) = object_sid.split()

            search_filter = "(|(primaryGroupID=%s)(memberOf=%s))" % (rid,
                                                                     group_dn)
            res = samdb.search(samdb.domain_dn(),
                               scope=ldb.SCOPE_SUBTREE,
                               expression=(search_filter),
                               attrs=["samAccountName", "cn"])

            if (len(res) == 0):
                return

            for msg in res:
                if full_dn:
                    self.outf.write("%s\n" % msg.get("dn"))
                    continue

                member_name = msg.get("samAccountName", idx=0)
                if member_name is None:
                    member_name = msg.get("cn", idx=0)
                self.outf.write("%s\n" % member_name)

        except Exception as e:
            raise CommandError(
                'Failed to list members of "%s" group ' % groupname, e)
Exemplo n.º 26
0
    def run(self, sitename, sambaopts=None, credopts=None, versionopts=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        url = lp.private_path("sam.ldb")

        if not os.path.exists(url):
            raise CommandError("secret database not found at %s " % url)
        samdb = SamDB(url=url,
                      session_info=system_session(),
                      credentials=creds,
                      lp=lp)

        samdb.transaction_start()
        try:
            ok = sites.delete_site(samdb, samdb.get_config_basedn(), sitename)
            samdb.transaction_commit()
        except sites.SiteException, e:
            samdb.transaction_cancel()
            raise CommandError("Error while removing site %s, error: %s" %
                               (sitename, str(e)))
Exemplo n.º 27
0
    def run(self, username=None, sambaopts=None, credopts=None,
            versionopts=None, H=None, filter=None, days=None, noexpiry=None):
        if username is None and filter is None:
            raise CommandError("Either the username or '--filter' must be specified!")

        if filter is None:
            filter = "(&(objectClass=user)(sAMAccountName=%s))" % (ldb.binary_encode(username))

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)

        samdb = SamDB(url=H, session_info=system_session(),
            credentials=creds, lp=lp)

        try:
            samdb.setexpiry(filter, days*24*3600, no_expiry_req=noexpiry)
        except Exception, msg:
            # FIXME: Catch more specific exception
            raise CommandError("Failed to set expiry for user '%s': %s" % (
                username or filter, msg))
Exemplo n.º 28
0
    def run(self, username, credopts=None, sambaopts=None, versionopts=None,
            H=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)

        try:
            samdb = SamDB(url=H, session_info=system_session(),
                          credentials=creds, lp=lp)
            samdb.deleteuser(username)
        except Exception, e:
            raise CommandError('Failed to remove user "%s"' % username, e)
Exemplo n.º 29
0
    def get_neighbours(self, info_type):
        req1 = drsuapi.DsReplicaGetInfoRequest1()
        req1.info_type = info_type
        try:
            (info_type, info) = self.drsuapi.DsReplicaGetInfo(
                self.drsuapi_handle, 1, req1)
        except Exception as e:
            raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)

        reps = [self.parse_neighbour(n) for n in info.array]
        return reps
Exemplo n.º 30
0
def drsuapi_connect(ctx):
    '''make a DRSUAPI connection to the server'''
    binding_options = "seal"
    if ctx.lp.get("log level") >= 5:
        binding_options += ",print"
    binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
    try:
        ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
        (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
    except Exception, e:
        raise CommandError("DRS connection to %s failed" % ctx.server, e)