Example #1
0
    def insta_creds(self, template=None, username=None, userpass=None, kerberos_state=None):

        if template is None:
            assert template is not None

        if username is not None:
            assert userpass is not None

        if username is None:
            assert userpass is None

            username = template.get_username()
            userpass = template.get_password()

        if kerberos_state is None:
            kerberos_state = template.get_kerberos_state()

        # get a copy of the global creds or a the passed in creds
        c = Credentials()
        c.set_username(username)
        c.set_password(userpass)
        c.set_domain(template.get_domain())
        c.set_realm(template.get_realm())
        c.set_workstation(template.get_workstation())
        c.set_gensec_features(c.get_gensec_features()
                              | gensec.FEATURE_SEAL)
        c.set_kerberos_state(kerberos_state)
        return c
Example #2
0
class KCCTests(samba.tests.TestCase):
    def setUp(self):
        super(KCCTests, self).setUp()
        self.lp = LoadParm()
        self.creds = Credentials()
        self.creds.guess(self.lp)
        self.creds.set_username(os.environ["USERNAME"])
        self.creds.set_password(os.environ["PASSWORD"])


    def test_list_dsas(self):
        my_kcc = kcc.KCC(unix_now, False, False, False, False)
        my_kcc.load_samdb("ldap://%s" % os.environ["SERVER"],
                          self.lp, self.creds)
        dsas = my_kcc.list_dsas()
        env = os.environ['TEST_ENV']
        for expected_dsa in ENV_DSAS[env]:
            self.assertIn(expected_dsa, dsas)

    def test_verify(self):
        """check that the KCC generates graphs that pass its own verify
        option. This is not a spectacular achievement when there are
        only a couple of nodes to connect, but it shows something.
        """
        my_kcc = kcc.KCC(unix_now, readonly=True, verify=True,
                         debug=False, dot_file_dir=None)

        my_kcc.run("ldap://%s" % os.environ["SERVER"],
                   self.lp, self.creds,
                   attempt_live_connections=False)
Example #3
0
    def setUp(self):
        super(DrsRodcTestCase, self).setUp()
        self.base_dn = self.ldb_dc1.get_default_basedn()

        rand = random.randint(1, 10000000)

        self.ou = "OU=test_drs_rodc%s,%s" % (rand, self.base_dn)
        self.ldb_dc1.add({
            "dn": self.ou,
            "objectclass": "organizationalUnit"
        })
        self.allowed_group = "CN=Allowed RODC Password Replication Group,CN=Users,%s" % self.base_dn

        self.site = self.ldb_dc1.server_site_name()
        self.rodc_name = "TESTRODCDRS%s" % rand
        self.rodc_pass = "******"
        self.computer_dn = "CN=%s,OU=Domain Controllers,%s" % (self.rodc_name, self.base_dn)


        self.rodc_ctx = dc_join(server=self.ldb_dc1.host_dns_name(), creds=self.get_credentials(), lp=self.get_loadparm(),
                                site=self.site, netbios_name=self.rodc_name,
                                targetdir=None, domain=None, machinepass=self.rodc_pass)
        self._create_rodc(self.rodc_ctx)
        self.rodc_ctx.create_tmp_samdb()
        self.tmp_samdb = self.rodc_ctx.tmp_samdb

        rodc_creds = Credentials()
        rodc_creds.guess(self.rodc_ctx.lp)
        rodc_creds.set_username(self.rodc_name+'$')
        rodc_creds.set_password(self.rodc_pass)
        self.rodc_creds = rodc_creds

        (self.drs, self.drs_handle) = self._ds_bind(self.dnsname_dc1)
        (self.rodc_drs, self.rodc_drs_handle) = self._ds_bind(self.dnsname_dc1, rodc_creds)
Example #4
0
    def _test_netlogon(self, binding, checkFunction):

        def isLastExpectedMessage(msg):
            return (
                msg["type"] == "Authorization" and
                msg["Authorization"]["serviceDescription"]  == "DCE/RPC" and
                msg["Authorization"]["authType"]            == "schannel" and
                msg["Authorization"]["transportProtection"] == "SEAL")

        if binding:
            binding = "[schannel,%s]" % binding
        else:
            binding = "[schannel]"

        machine_creds = Credentials()
        machine_creds.guess(self.get_loadparm())
        machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
        machine_creds.set_password(self.machinepass)
        machine_creds.set_username(self.netbios_name + "$")

        netlogon_conn = netlogon.netlogon("ncalrpc:%s" % binding,
                                          self.get_loadparm(),
                                          machine_creds)

        messages = self.waitForMessages(isLastExpectedMessage, netlogon_conn)
        checkFunction(messages)
    def _test_netlogon(self, name, pwd, status, checkFunction):

        def isLastExpectedMessage(msg):
            return (
                msg["type"] == "Authentication" and
                msg["Authentication"]["serviceDescription"] == "NETLOGON" and
                msg["Authentication"]["authDescription"] ==
                "ServerAuthenticate" and
                msg["Authentication"]["status"] == status)

        machine_creds = Credentials()
        machine_creds.guess(self.get_loadparm())
        machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
        machine_creds.set_password(pwd)
        machine_creds.set_username(name + "$")

        try:
            netlogon.netlogon("ncalrpc:[schannel]",
                              self.get_loadparm(),
                              machine_creds)
            self.fail("NTSTATUSError not raised")
        except NTSTATUSError:
            pass

        messages = self.waitForMessages(isLastExpectedMessage)
        checkFunction(messages)
Example #6
0
 def get_creds(self, target_username, target_password):
     creds_tmp = Credentials()
     creds_tmp.set_username(target_username)
     creds_tmp.set_password(target_password)
     creds_tmp.set_domain(creds.get_domain())
     creds_tmp.set_realm(creds.get_realm())
     creds_tmp.set_workstation(creds.get_workstation())
     creds_tmp.set_gensec_features(creds_tmp.get_gensec_features() | gensec.FEATURE_SEAL)
     return creds_tmp
Example #7
0
    def join_replicate(ctx):
        '''replicate the SAM'''

        print "Starting replication"
        ctx.local_samdb.transaction_start()
        try:
            source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
            if ctx.ntds_guid is None:
                print("Using DS_BIND_GUID_W2K3")
                destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
            else:
                destination_dsa_guid = ctx.ntds_guid

            if ctx.RODC:
                repl_creds = Credentials()
                repl_creds.guess(ctx.lp)
                repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
                repl_creds.set_username(ctx.samname)
                repl_creds.set_password(ctx.acct_pass)
            else:
                repl_creds = ctx.creds

            binding_options = "seal"
            if int(ctx.lp.get("log level")) >= 5:
                binding_options += ",print"
            repl = drs_utils.drs_Replicate(
                "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
                ctx.lp, repl_creds, ctx.local_samdb)

            repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
                    destination_dsa_guid, schema=True, rodc=ctx.RODC,
                    replica_flags=ctx.replica_flags)
            repl.replicate(ctx.config_dn, source_dsa_invocation_id,
                    destination_dsa_guid, rodc=ctx.RODC,
                    replica_flags=ctx.replica_flags)
            if not ctx.subdomain:
                repl.replicate(ctx.base_dn, source_dsa_invocation_id,
                               destination_dsa_guid, rodc=ctx.RODC,
                               replica_flags=ctx.domain_replica_flags)
            if ctx.RODC:
                repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
                        destination_dsa_guid,
                        exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
                repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
                        destination_dsa_guid,
                        exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
            ctx.repl = repl
            ctx.source_dsa_invocation_id = source_dsa_invocation_id
            ctx.destination_dsa_guid = destination_dsa_guid

            print "Committing SAM database"
        except:
            ctx.local_samdb.transaction_cancel()
            raise
        else:
            ctx.local_samdb.transaction_commit()
Example #8
0
class NtlmDisabledTests(TestCase):

    def setUp(self):
        super(NtlmDisabledTests, self).setUp()

        self.lp          = self.get_loadparm()
        self.server      = os.getenv("SERVER")

        self.creds = Credentials()
        self.creds.guess(self.lp)
        self.creds.set_username(os.getenv("USERNAME"))
        self.creds.set_domain(self.server)
        self.creds.set_password(os.getenv("PASSWORD"))
        self.creds.set_kerberos_state(DONT_USE_KERBEROS)

    def tearDown(self):
        super(NtlmDisabledTests, self).tearDown()

    def test_ntlm_connection(self):
        try:
            conn = srvsvc.srvsvc("ncacn_np:%s[smb2,ntlm]" % self.server, self.lp, self.creds)

            self.assertIsNotNone(conn)
        except NTSTATUSError as e:
            # NTLM might be blocked on this server
            enum = ctypes.c_uint32(e[0]).value
            if enum == ntstatus.NT_STATUS_NTLM_BLOCKED:
                self.fail("NTLM is disabled on this server")
            else:
                raise

    def test_samr_change_password(self):
        self.creds.set_kerberos_state(MUST_USE_KERBEROS)
        conn = samr.samr("ncacn_np:%s[krb5,seal,smb2]" % os.getenv("SERVER"))

        # we want to check whether this gets rejected outright because NTLM is
        # disabled, so we don't actually need to encrypt a valid password here
        server = lsa.String()
        server.string = self.server
        username = lsa.String()
        username.string = os.getenv("USERNAME")

        try:
            conn.ChangePasswordUser2(server, username, None, None, True, None, None)
        except NTSTATUSError as e:
            # changing passwords should be rejected when NTLM is disabled
            enum = ctypes.c_uint32(e[0]).value
            if enum == ntstatus.NT_STATUS_NTLM_BLOCKED:
                self.fail("NTLM is disabled on this server")
            elif enum == ntstatus.NT_STATUS_WRONG_PASSWORD:
                # expected error case when NTLM is enabled
                pass
            else:
                raise
 def get_creds(self, target_username, target_password):
     creds_tmp = Credentials()
     creds_tmp.set_username(target_username)
     creds_tmp.set_password(target_password)
     creds_tmp.set_domain(creds.get_domain())
     creds_tmp.set_realm(creds.get_realm())
     creds_tmp.set_workstation(creds.get_workstation())
     creds_tmp.set_gensec_features(creds_tmp.get_gensec_features()
                                   | gensec.FEATURE_SEAL)
     creds_tmp.set_kerberos_state(DONT_USE_KERBEROS) # kinit is too expensive to use in a tight loop
     return creds_tmp
Example #10
0
 def get_ldb_connection(self, target_username, target_password):
     creds_tmp = Credentials()
     creds_tmp.set_username(target_username)
     creds_tmp.set_password(target_password)
     creds_tmp.set_domain(creds.get_domain())
     creds_tmp.set_realm(creds.get_realm())
     creds_tmp.set_workstation(creds.get_workstation())
     creds_tmp.set_gensec_features(creds_tmp.get_gensec_features()
                                   | gensec.FEATURE_SEAL)
     ldb_target = SamDB(url=ldaphost, credentials=creds_tmp, lp=lp)
     return ldb_target
Example #11
0
 def get_ldb_connection(self, target_username, target_password):
     creds_tmp = Credentials()
     creds_tmp.set_username(target_username)
     creds_tmp.set_password(target_password)
     creds_tmp.set_domain(creds.get_domain())
     creds_tmp.set_realm(creds.get_realm())
     creds_tmp.set_workstation(creds.get_workstation())
     creds_tmp.set_gensec_features(creds_tmp.get_gensec_features()
                                   | gensec.FEATURE_SEAL)
     creds_tmp.set_kerberos_state(DONT_USE_KERBEROS) # kinit is too expensive to use in a tight loop
     ldb_target = SamDB(url=ldaphost, credentials=creds_tmp, lp=lp)
     return ldb_target
Example #12
0
 def get_ldb_connection(self, username, password, ldaphost):
     """Returns an LDB connection using the specified user's credentials"""
     creds = self.get_credentials()
     creds_tmp = Credentials()
     creds_tmp.set_username(username)
     creds_tmp.set_password(password)
     creds_tmp.set_domain(creds.get_domain())
     creds_tmp.set_realm(creds.get_realm())
     creds_tmp.set_workstation(creds.get_workstation())
     creds_tmp.set_gensec_features(creds_tmp.get_gensec_features()
                                   | gensec.FEATURE_SEAL)
     return samba.tests.connect_samdb(ldaphost, credentials=creds_tmp)
Example #13
0
    def test_msDSRevealedUsers_using_other_RODC(self):
        """
        Ensure that the machine account is tied to the destination DSA.
        """
        # Create a new identical RODC with just the first letter missing
        other_rodc_name = self.rodc_name[1:]
        other_rodc_ctx = dc_join(server=self.ldb_dc1.host_dns_name(), creds=self.get_credentials(), lp=self.get_loadparm(),
                                 site=self.site, netbios_name=other_rodc_name,
                                 targetdir=None, domain=None, machinepass=self.rodc_pass)
        self._create_rodc(other_rodc_ctx)

        other_rodc_creds = Credentials()
        other_rodc_creds.guess(other_rodc_ctx.lp)
        other_rodc_creds.set_username(other_rodc_name+'$')
        other_rodc_creds.set_password(self.rodc_pass)

        (other_rodc_drs, other_rodc_drs_handle) = self._ds_bind(self.dnsname_dc1, other_rodc_creds)

        rand = random.randint(1, 10000000)
        expected_user_attributes = [drsuapi.DRSUAPI_ATTID_lmPwdHistory,
                                    drsuapi.DRSUAPI_ATTID_supplementalCredentials,
                                    drsuapi.DRSUAPI_ATTID_ntPwdHistory,
                                    drsuapi.DRSUAPI_ATTID_unicodePwd,
                                    drsuapi.DRSUAPI_ATTID_dBCSPwd]

        user_name = "test_rodcF_%s" % rand
        user_dn = "CN=%s,%s" % (user_name, self.ou)
        self.ldb_dc1.add({
            "dn": user_dn,
            "objectclass": "user",
            "sAMAccountName": user_name
        })

        # Store some secret on this user
        self.ldb_dc1.setpassword("(sAMAccountName=%s)" % user_name, 'penguin12#', False, user_name)
        self.ldb_dc1.add_remove_group_members("Allowed RODC Password Replication Group",
                                              [user_name],
                                              add_members_operation=True)

        req10 = self._getnc_req10(dest_dsa=str(other_rodc_ctx.ntds_guid),
                                  invocation_id=self.ldb_dc1.get_invocation_id(),
                                  nc_dn_str=user_dn,
                                  exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET,
                                  partial_attribute_set=drs_get_rodc_partial_attribute_set(self.ldb_dc1, self.tmp_samdb),
                                  max_objects=133,
                                  replica_flags=0)

        try:
            (level, ctr) = self.rodc_drs.DsGetNCChanges(self.rodc_drs_handle, 10, req10)
            self.fail("Successfully replicated secrets to an RODC that shouldn't have been replicated.")
        except WERRORError as (enum, estr):
            self.assertEquals(enum, 8630) # ERROR_DS_DRA_SECRETS_DENIED
Example #14
0
 def get_service_creds(self, allow_missing_password=False):
     c = Credentials()
     c.guess()
     domain = samba.tests.env_get_var_value('DOMAIN')
     realm = samba.tests.env_get_var_value('REALM')
     username = samba.tests.env_get_var_value('SERVICE_USERNAME')
     password = samba.tests.env_get_var_value(
         'SERVICE_PASSWORD', allow_missing=allow_missing_password)
     c.set_domain(domain)
     c.set_realm(realm)
     c.set_username(username)
     if password is not None:
         c.set_password(password)
     return c
Example #15
0
    def join_replicate(ctx):
        '''replicate the SAM'''

        print "Starting replication"
        ctx.local_samdb.transaction_start()
        try:
            source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
            destination_dsa_guid = ctx.ntds_guid

            if ctx.RODC:
                repl_creds = Credentials()
                repl_creds.guess(ctx.lp)
                repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
                repl_creds.set_username(ctx.samname)
                repl_creds.set_password(ctx.acct_pass)
            else:
                repl_creds = ctx.creds

            binding_options = "seal"
            if ctx.lp.get("debug level") >= 5:
                binding_options += ",print"
            repl = drs_utils.drs_Replicate(
                "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
                ctx.lp, repl_creds, ctx.local_samdb)

            repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
                    destination_dsa_guid, schema=True, rodc=ctx.RODC,
                    replica_flags=ctx.replica_flags)
            repl.replicate(ctx.config_dn, source_dsa_invocation_id,
                    destination_dsa_guid, rodc=ctx.RODC,
                    replica_flags=ctx.replica_flags)
            repl.replicate(ctx.base_dn, source_dsa_invocation_id,
                    destination_dsa_guid, rodc=ctx.RODC,
                    replica_flags=ctx.replica_flags)
            if ctx.RODC:
                repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
                        destination_dsa_guid,
                        exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
                repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
                        destination_dsa_guid,
                        exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)

            print "Committing SAM database"
        except:
            ctx.local_samdb.transaction_cancel()
            raise
        else:
            ctx.local_samdb.transaction_commit()
Example #16
0
    def create_account(self, name, machine_account=False, spn=None, upn=None):
        '''Create an account for testing.
           The dn of the created account is added to self.accounts,
           which is used by tearDown to clean up the created accounts.
        '''
        dn = "cn=%s,%s" % (name, self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, dn)
        if machine_account:
            object_class = "computer"
            account_name = "%s$" % name
            account_control = str(UF_WORKSTATION_TRUST_ACCOUNT)
        else:
            object_class = "user"
            account_name = name
            account_control = str(UF_NORMAL_ACCOUNT)

        password = generate_random_password(32, 32)
        utf16pw = ('"%s"' % password).encode('utf-16-le')

        details = {
            "dn": dn,
            "objectclass": object_class,
            "sAMAccountName": account_name,
            "userAccountControl": account_control,
            "unicodePwd": utf16pw
        }
        if spn is not None:
            details["servicePrincipalName"] = spn
        if upn is not None:
            details["userPrincipalName"] = upn
        self.ldb.add(details)

        creds = Credentials()
        creds.guess(self.lp)
        creds.set_realm(self.ldb.domain_dns_name().upper())
        creds.set_domain(self.ldb.domain_netbios_name().upper())
        creds.set_password(password)
        creds.set_username(account_name)
        if machine_account:
            creds.set_workstation(name)
        #
        # Save the account name so it can be deleted in the tearDown
        self.accounts.append(dn)

        return (creds, dn)
Example #17
0
def credenciales(username, password, parametros):
    """
    Más que nada, encapsulo un par de líneas sobre el trabajo con Credentials()
    Rompe un poco la idea de inyección, pero así las cosas
    """
    cred = Credentials()
    dominio = parametros.get('workgroup')
    
    cred.set_username(username)
    cred.set_password(password)
    cred.set_domain(dominio)
    
    # TODO: ¿Este tiene algún efecto?
    cred.set_workstation("")

    return cred
Example #18
0
 def get_user_and_ldb(self, username, password, hostname=ldaphost):
     """Get a connection for a temporarily user that will vanish as soon as
     the test is over."""
     user = self.ldb.newuser(username, password)
     creds_tmp = Credentials()
     creds_tmp.set_username(username)
     creds_tmp.set_password(password)
     creds_tmp.set_domain(creds.get_domain())
     creds_tmp.set_realm(creds.get_realm())
     creds_tmp.set_workstation(creds.get_workstation())
     creds_tmp.set_gensec_features(creds_tmp.get_gensec_features()
                                   | gensec.FEATURE_SEAL)
     creds_tmp.set_kerberos_state(DONT_USE_KERBEROS)
     ldb_target = SamDB(url=hostname, credentials=creds_tmp, lp=lp)
     self.addCleanup(delete_force, self.ldb, self.get_user_dn(username))
     return (user, ldb_target)
Example #19
0
 def authenticate(self, usuario, password):
     # Connect to samba and attempt to authenticate this user
     print("SambaServer.authenticate: authenticating with %s and %s" %
           (usuario, password))
     lp = param.LoadParm()
     badge = Credentials()
     badge.guess(lp)
     badge.set_username(usuario)
     badge.set_password(password)
     # Intento la conexion.
     cx = SamDB(url='ldap://localhost', lp=lp, credentials=badge)
     print("cx returned: %s" % cx)
     # Get the domain from the SamDB and store it
     self.domain = cx.domain_dn()
     # Listo, la gracia es que si logre autenticarme con estos datos, y hay algun
     # resultado de mis acciones, voy a devolver algo.
     return cx
Example #20
0
    def netlogon(self):
        server = os.environ["SERVER"]
        host = os.environ["SERVER_IP"]
        lp = self.get_loadparm()

        credentials = self.get_credentials()

        session = system_session()
        ldb = SamDB(url="ldap://%s" % host,
                    session_info=session,
                    credentials=credentials,
                    lp=lp)
        machine_pass = samba.generate_random_password(32, 32)
        machine_name = MACHINE_NAME
        machine_dn = "cn=%s,%s" % (machine_name, ldb.domain_dn())

        delete_force(ldb, machine_dn)

        utf16pw = ('"%s"' % get_string(machine_pass)).encode('utf-16-le')
        ldb.add({
            "dn":
            machine_dn,
            "objectclass":
            "computer",
            "sAMAccountName":
            "%s$" % machine_name,
            "userAccountControl":
            str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
            "unicodePwd":
            utf16pw
        })

        machine_creds = Credentials()
        machine_creds.guess(lp)
        machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
        machine_creds.set_kerberos_state(DONT_USE_KERBEROS)
        machine_creds.set_password(machine_pass)
        machine_creds.set_username(machine_name + "$")
        machine_creds.set_workstation(machine_name)

        netlogon.netlogon("ncacn_ip_tcp:%s[schannel,seal]" % server, lp,
                          machine_creds)

        delete_force(ldb, machine_dn)
Example #21
0
def get_ad_binddn_from_name(base, server, username, password):
	lp = LoadParm()
	creds = Credentials()
	creds.guess(lp)
	creds.set_username(username)
	creds.set_password(password)
	binddn = 'cn=%s,cn=users,%s' % (ldap.dn.escape_dn_chars(username), base)
	try:
		samdb = SamDB(url='ldap://%s' % server, session_info=system_session(), credentials=creds, lp=lp)
		res = samdb.search(
			base,
			scope=ldb.SCOPE_SUBTREE,
			expression=ldap.filter.filter_format('(samAccountName=%s)', [username, ]),
			attrs=['samaccountname'])
		if res.count == 1:
			binddn = res.msgs[0].get('dn', idx=0).extended_str()
	except ldb.LdbError as ex:
		MODULE.warn('get_dn_from_name() could not get binddn for user %s: %s' % (username, ex))
	return binddn
Example #22
0
class KCCTests(samba.tests.TestCase):
    def setUp(self):
        super(KCCTests, self).setUp()
        self.lp = LoadParm()
        self.creds = Credentials()
        self.creds.guess(self.lp)
        self.creds.set_username(os.environ["USERNAME"])
        self.creds.set_password(os.environ["PASSWORD"])

    def test_list_dsas(self):
        my_kcc = kcc.KCC(unix_now, False, False, False, False)
        my_kcc.load_samdb("ldap://%s" % os.environ["SERVER"], self.lp,
                          self.creds)
        try:
            dsas = my_kcc.list_dsas()
        except kcc.KCCError as e:
            self.fail("kcc.list_dsas failed with %s" % e)
        env = os.environ['TEST_ENV']
        for expected_dsa in ENV_DSAS[env]:
            self.assertIn(expected_dsa, dsas)

    def test_verify(self):
        """check that the KCC generates graphs that pass its own verify
        option. This is not a spectacular achievement when there are
        only a couple of nodes to connect, but it shows something.
        """
        my_kcc = kcc.KCC(unix_now,
                         readonly=True,
                         verify=True,
                         debug=False,
                         dot_file_dir=None)

        # As this is flapping with errors under python3, we catch
        # exceptions and turn them into failures..
        try:
            my_kcc.run("ldap://%s" % os.environ["SERVER"],
                       self.lp,
                       self.creds,
                       attempt_live_connections=False)
        except (samba.kcc.graph_utils.GraphError, kcc.KCCError):
            import traceback
            traceback.print_exc()
            self.fail()
Example #23
0
def get_dns_zones():
    request_filter = dnsserver.DNS_ZONE_REQUEST_PRIMARY
    server = '127.0.0.1'
    binding_str = 'ncacn_ip_tcp:%s[sign]' % server
    cred_data = open('/vapour/dnsquery').read().split(':')

    creds = Credentials()
    creds.guess(lp)
    creds.set_username(cred_data[0])
    creds.set_password(cred_data[1].rstrip())

    dns_conn = dnsserver.dnsserver(binding_str, lp, creds)
    client_version = dnsserver.DNS_CLIENT_VERSION_LONGHORN

    typeid, res = dns_conn.DnssrvComplexOperation2(
        client_version, 0, server, None, 'EnumZones',
        dnsserver.DNSSRV_TYPEID_DWORD, request_filter)

    return dict(res)
Example #24
0
 def _get_smb_connection(self, service='SysVol'):
     # Create options like if we were using command line
     parser = optparse.OptionParser()
     sambaopts = options.SambaOptions(parser)
     # Samba options
     parm = sambaopts.get_loadparm()
     s3_lp = s3param.get_context()
     s3_lp.load(parm.configfile)
     # Build credentials from credential options
     creds = Credentials()
     # Credentials need username and realm to be not empty strings to work
     creds.set_username('NOTEMPTY')
     creds.set_realm('NOTEMPTY')
     # Connect to SMB using kerberos
     creds.set_kerberos_state(MUST_USE_KERBEROS)
     # Create connection
     conn = libsmb.Conn(self._get_server_name(),
                        service,
                        lp=parm,
                        creds=creds,
                        sign=False)
     return conn
Example #25
0
class NetlogonServiceTests(TestCase):

    def setUp(self):
        super(NetlogonServiceTests, self).setUp()

        self.server      = os.environ["SERVER"]
        self.lp          = self.get_loadparm()
        self.creds = Credentials()

        # prefer the DC user/password in environments that have it
        if "DC_USERNAME" in os.environ and "DC_PASSWORD" in os.environ:
            self.creds.set_username(os.environ["DC_USERNAME"])
            self.creds.set_password(os.environ["DC_PASSWORD"])
        else:
            self.creds.set_username(os.environ["USERNAME"])
            self.creds.set_password(os.environ["PASSWORD"])

        self.creds.guess(self.lp)

    def tearDown(self):
        super(NetlogonServiceTests, self).tearDown()

    def test_have_netlogon_connection(self):
        try:
            c = self.get_netlogon_connection()
            self.assertIsNotNone(c)
        except NTSTATUSError as e:
            # On non-DC test environments, netlogon should not be running on
            # the server, so we expect the test to fail here
            enum = ctypes.c_uint32(e.args[0]).value
            if enum == ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND:
                self.fail("netlogon service is not running")
            else:
                raise

    # Establish netlogon connection over NP
    def get_netlogon_connection(self):
        return netlogon.netlogon("ncacn_np:%s[seal]" % self.server, self.lp,
                                 self.creds)
Example #26
0
def make_creds(username, password, kerberos_state=None):
    # use the global CREDS as a template
    c = Credentials()
    c.set_username(username)
    c.set_password(password)
    c.set_domain(CREDS.get_domain())
    c.set_realm(CREDS.get_realm())
    c.set_workstation(CREDS.get_workstation())

    if kerberos_state is None:
        kerberos_state = CREDS.get_kerberos_state()
    c.set_kerberos_state(kerberos_state)

    print '-' * 73
    if kerberos_state == MUST_USE_KERBEROS:
        print "we seem to be using kerberos for %s %s" % (username, password)
    elif kerberos_state == DONT_USE_KERBEROS:
        print "NOT using kerberos for %s %s" % (username, password)
    else:
        print "kerberos state is %s" % kerberos_state

    c.set_gensec_features(c.get_gensec_features() | gensec.FEATURE_SEAL)
    return c
    def _test_netlogon(self, name, pwd, status, checkFunction):
        def isLastExpectedMessage(msg):
            return (msg["type"] == "Authentication" and
                    msg["Authentication"]["serviceDescription"] == "NETLOGON"
                    and msg["Authentication"]["authDescription"]
                    == "ServerAuthenticate"
                    and msg["Authentication"]["status"] == status)

        machine_creds = Credentials()
        machine_creds.guess(self.get_loadparm())
        machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
        machine_creds.set_password(pwd)
        machine_creds.set_username(name + "$")

        try:
            netlogon.netlogon("ncalrpc:[schannel]", self.get_loadparm(),
                              machine_creds)
            self.fail("NTSTATUSError not raised")
        except NTSTATUSError:
            pass

        messages = self.waitForMessages(isLastExpectedMessage)
        checkFunction(messages)
Example #28
0
    def _test_netlogon(self, binding, checkFunction):
        def isLastExpectedMessage(msg):
            return (msg["type"] == "Authorization"
                    and msg["Authorization"]["serviceDescription"] == "DCE/RPC"
                    and msg["Authorization"]["authType"] == "schannel"
                    and msg["Authorization"]["transportProtection"] == "SEAL")

        if binding:
            binding = "[schannel,%s]" % binding
        else:
            binding = "[schannel]"

        machine_creds = Credentials()
        machine_creds.guess(self.get_loadparm())
        machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
        machine_creds.set_password(self.machinepass)
        machine_creds.set_username(self.netbios_name + "$")

        netlogon_conn = netlogon.netlogon("ncalrpc:%s" % binding,
                                          self.get_loadparm(), machine_creds)

        messages = self.waitForMessages(isLastExpectedMessage, netlogon_conn)
        checkFunction(messages)
Example #29
0
	def getUsers(self):
		lp = param.LoadParm()
		badge = Credentials()
		badge.guess(lp)
		badge.set_username('Administrator')
		badge.set_password('pa$$w0rd!')

		print("Getting users")
					
		# Binding...
		cx = SamDB(url='ldap://localhost', lp=lp, credentials=badge)

		# Search...
		search_result = cx.search('DC=kajohansen,DC=com', scope=2, expression='(objectClass=user)', attrs=["samaccountname"])
		
		users = [] # list to hold our users
		
		# Results...
		for username in search_result:
# 			print("User: %s" % username.get("samaccountname", idx=0))
			users.append(username.get("samaccountname", idx=0))
		
		return users
Example #30
0
    def setUp(self):
        super(DrsRodcTestCase, self).setUp()
        self.base_dn = self.ldb_dc1.get_default_basedn()

        rand = random.randint(1, 10000000)

        self.ou = "OU=test_drs_rodc%s,%s" % (rand, self.base_dn)
        self.ldb_dc1.add({"dn": self.ou, "objectclass": "organizationalUnit"})
        self.allowed_group = "CN=Allowed RODC Password Replication Group,CN=Users,%s" % self.base_dn

        self.site = self.ldb_dc1.server_site_name()
        self.rodc_name = "TESTRODCDRS%s" % rand
        self.rodc_pass = "******"
        self.computer_dn = "CN=%s,OU=Domain Controllers,%s" % (self.rodc_name,
                                                               self.base_dn)

        self.rodc_ctx = dc_join(server=self.ldb_dc1.host_dns_name(),
                                creds=self.get_credentials(),
                                lp=self.get_loadparm(),
                                site=self.site,
                                netbios_name=self.rodc_name,
                                targetdir=None,
                                domain=None,
                                machinepass=self.rodc_pass)
        self._create_rodc(self.rodc_ctx)
        self.rodc_ctx.create_tmp_samdb()
        self.tmp_samdb = self.rodc_ctx.tmp_samdb

        rodc_creds = Credentials()
        rodc_creds.guess(self.rodc_ctx.lp)
        rodc_creds.set_username(self.rodc_name + '$')
        rodc_creds.set_password(self.rodc_pass)
        self.rodc_creds = rodc_creds

        (self.drs, self.drs_handle) = self._ds_bind(self.dnsname_dc1)
        (self.rodc_drs,
         self.rodc_drs_handle) = self._ds_bind(self.dnsname_dc1, rodc_creds)
Example #31
0
    def test_modify_dsheuristics_userPassword(self):
        print("Performs testing about reading userPassword between dsHeuristic modifies")

        # Make sure userPassword cannot be read
        self.ldb.set_dsheuristics("000000000")

        # Open a new connection (with dsHeuristic=000000000)
        ldb1 = SamDB(url=host, session_info=system_session(lp),
                     credentials=creds, lp=lp)

        # Set userPassword to be read
        # This setting only affects newer connections (ldb2)
        ldb1.set_dsheuristics("000000001")
        time.sleep(1)

        m = Message()
        m.dn = Dn(ldb1, "cn=testuser,cn=users," + self.base_dn)
        m["userPassword"] = MessageElement("thatsAcomplPASS1", FLAG_MOD_REPLACE,
          "userPassword")
        ldb1.modify(m)

        res = ldb1.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # userPassword cannot be read, despite the dsHeuristic setting
        self.assertTrue(len(res) == 1)
        self.assertFalse("userPassword" in res[0])

        # Open another new connection (with dsHeuristic=000000001)
        ldb2 = SamDB(url=host, session_info=system_session(lp),
                     credentials=creds, lp=lp)

        # Set userPassword to be unreadable
        # This setting does not affect this connection
        ldb2.set_dsheuristics("000000000")
        time.sleep(1)

        res = ldb2.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # Check that userPassword was not stored from ldb1
        self.assertTrue(len(res) == 1)
        self.assertFalse("userPassword" in res[0])

        m = Message()
        m.dn = Dn(ldb2, "cn=testuser,cn=users," + self.base_dn)
        m["userPassword"] = MessageElement("thatsAcomplPASS2", FLAG_MOD_REPLACE,
          "userPassword")
        ldb2.modify(m)

        res = ldb2.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # userPassword can be read in this connection
        # This is regardless of the current dsHeuristics setting
        self.assertTrue(len(res) == 1)
        self.assertTrue("userPassword" in res[0])
        self.assertEquals(res[0]["userPassword"][0], "thatsAcomplPASS2")

        # Only password from ldb1 is the user's password
        creds2 = Credentials()
        creds2.set_username("testuser")
        creds2.set_password("thatsAcomplPASS1")
        creds2.set_domain(creds.get_domain())
        creds2.set_realm(creds.get_realm())
        creds2.set_workstation(creds.get_workstation())
        creds2.set_gensec_features(creds2.get_gensec_features()
                                   | gensec.FEATURE_SEAL)

        try:
            SamDB(url=host, credentials=creds2, lp=lp)
        except:
            self.fail("testuser used the wrong password")

        ldb3 = SamDB(url=host, session_info=system_session(lp),
                     credentials=creds, lp=lp)

        # Check that userPassword was stored from ldb2
        res = ldb3.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # userPassword can be read
        self.assertTrue(len(res) == 1)
        self.assertTrue("userPassword" in res[0])
        self.assertEquals(res[0]["userPassword"][0], "thatsAcomplPASS2")

        # Reset the test "dSHeuristics" (reactivate "userPassword" pwd changes)
        self.ldb.set_dsheuristics("000000001")
Example #32
0
    def setUp(self):
        super(PasswordTests, self).setUp()
        self.ldb = SamDB(url=host, session_info=system_session(lp), credentials=creds, lp=lp)

        # Gets back the basedn
        base_dn = self.ldb.domain_dn()

        # Gets back the configuration basedn
        configuration_dn = self.ldb.get_config_basedn().get_linearized()

        # Get the old "dSHeuristics" if it was set
        dsheuristics = self.ldb.get_dsheuristics()

        # Set the "dSHeuristics" to activate the correct "userPassword" behaviour
        self.ldb.set_dsheuristics("000000001")

        # Reset the "dSHeuristics" as they were before
        self.addCleanup(self.ldb.set_dsheuristics, dsheuristics)

        # Get the old "minPwdAge"
        minPwdAge = self.ldb.get_minPwdAge()

        # Set it temporarily to "0"
        self.ldb.set_minPwdAge("0")
        self.base_dn = self.ldb.domain_dn()

        # Reset the "minPwdAge" as it was before
        self.addCleanup(self.ldb.set_minPwdAge, minPwdAge)

        # (Re)adds the test user "testuser" with no password atm
        delete_force(self.ldb, "cn=testuser,cn=users," + self.base_dn)
        self.ldb.add({
             "dn": "cn=testuser,cn=users," + self.base_dn,
             "objectclass": "user",
             "sAMAccountName": "testuser"})

        # Tests a password change when we don't have any password yet with a
        # wrong old password
        try:
            self.ldb.modify_ldif("""
dn: cn=testuser,cn=users,""" + self.base_dn + """
changetype: modify
delete: userPassword
userPassword: noPassword
add: userPassword
userPassword: thatsAcomplPASS2
""")
            self.fail()
        except LdbError as e:
            (num, msg) = e.args
            self.assertEquals(num, ERR_CONSTRAINT_VIOLATION)
            # Windows (2008 at least) seems to have some small bug here: it
            # returns "0000056A" on longer (always wrong) previous passwords.
            self.assertTrue('00000056' in msg)

        # Sets the initial user password with a "special" password change
        # I think that this internally is a password set operation and it can
        # only be performed by someone which has password set privileges on the
        # account (at least in s4 we do handle it like that).
        self.ldb.modify_ldif("""
dn: cn=testuser,cn=users,""" + self.base_dn + """
changetype: modify
delete: userPassword
add: userPassword
userPassword: thatsAcomplPASS1
""")

        # But in the other way around this special syntax doesn't work
        try:
            self.ldb.modify_ldif("""
dn: cn=testuser,cn=users,""" + self.base_dn + """
changetype: modify
delete: userPassword
userPassword: thatsAcomplPASS1
add: userPassword
""")
            self.fail()
        except LdbError as e1:
            (num, _) = e1.args
            self.assertEquals(num, ERR_CONSTRAINT_VIOLATION)

        # Enables the user account
        self.ldb.enable_account("(sAMAccountName=testuser)")

        # Open a second LDB connection with the user credentials. Use the
        # command line credentials for informations like the domain, the realm
        # and the workstation.
        creds2 = Credentials()
        creds2.set_username("testuser")
        creds2.set_password("thatsAcomplPASS1")
        creds2.set_domain(creds.get_domain())
        creds2.set_realm(creds.get_realm())
        creds2.set_workstation(creds.get_workstation())
        creds2.set_gensec_features(creds2.get_gensec_features()
                                                          | gensec.FEATURE_SEAL)
        self.ldb2 = SamDB(url=host, credentials=creds2, lp=lp)
class PyKrb5CredentialsTests(TestCase):
    def setUp(self):
        super(PyKrb5CredentialsTests, self).setUp()

        self.server = os.environ["SERVER"]
        self.domain = os.environ["DOMAIN"]
        self.host = os.environ["SERVER_IP"]
        self.lp = self.get_loadparm()

        self.credentials = self.get_credentials()

        self.session = system_session()
        self.ldb = SamDB(url="ldap://%s" % self.host,
                         session_info=self.session,
                         credentials=self.credentials,
                         lp=self.lp)

        self.create_machine_account()

    def tearDown(self):
        super(PyKrb5CredentialsTests, self).tearDown()
        delete_force(self.ldb, self.machine_dn)

    def test_get_named_ccache(self):
        name = "MEMORY:py_creds_machine"
        ccache = self.machine_creds.get_named_ccache(self.lp, name)
        self.assertEqual(ccache.get_name(), name)

    def test_get_unnamed_ccache(self):
        ccache = self.machine_creds.get_named_ccache(self.lp)
        self.assertIsNotNone(ccache.get_name())

    def test_set_named_ccache(self):
        ccache = self.machine_creds.get_named_ccache(self.lp)

        creds = Credentials()
        creds.set_named_ccache(ccache.get_name())

        ccache2 = creds.get_named_ccache(self.lp)
        self.assertEqual(ccache.get_name(), ccache2.get_name())

    #
    # Create the machine account
    def create_machine_account(self):
        self.machine_pass = samba.generate_random_password(32, 32)
        self.machine_name = MACHINE_NAME
        self.machine_dn = "cn=%s,%s" % (self.machine_name,
                                        self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, self.machine_dn)
        # get unicode str for both py2 and py3
        pass_unicode = self.machine_pass.encode('utf-8').decode('utf-8')
        utf16pw = u'"{0}"'.format(pass_unicode).encode('utf-16-le')
        self.ldb.add({
            "dn":
            self.machine_dn,
            "objectclass":
            "computer",
            "sAMAccountName":
            "%s$" % self.machine_name,
            "userAccountControl":
            str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
            "unicodePwd":
            utf16pw
        })

        self.machine_creds = Credentials()
        self.machine_creds.guess(self.get_loadparm())
        self.machine_creds.set_password(self.machine_pass)
        self.machine_creds.set_username(self.machine_name + "$")
        self.machine_creds.set_workstation(self.machine_name)
Example #34
0
    def test_modify_dsheuristics_userPassword(self):
        print("Performs testing about reading userPassword between dsHeuristic modifies")

        # Make sure userPassword cannot be read
        self.ldb.set_dsheuristics("000000000")

        # Open a new connection (with dsHeuristic=000000000)
        ldb1 = SamDB(url=host, session_info=system_session(lp),
                     credentials=creds, lp=lp)

        # Set userPassword to be read
        # This setting only affects newer connections (ldb2)
        ldb1.set_dsheuristics("000000001")
        time.sleep(1)

        m = Message()
        m.dn = Dn(ldb1, "cn=testuser,cn=users," + self.base_dn)
        m["userPassword"] = MessageElement("thatsAcomplPASS1", FLAG_MOD_REPLACE,
          "userPassword")
        ldb1.modify(m)

        res = ldb1.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # userPassword cannot be read, it wasn't set, instead the
        # password was
        self.assertTrue(len(res) == 1)
        self.assertFalse("userPassword" in res[0])

        # Open another new connection (with dsHeuristic=000000001)
        ldb2 = SamDB(url=host, session_info=system_session(lp),
                     credentials=creds, lp=lp)

        res = ldb2.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # Check on the new connection that userPassword was not stored
        # from ldb1 or is not readable
        self.assertTrue(len(res) == 1)
        self.assertFalse("userPassword" in res[0])

        # Set userPassword to be readable
        # This setting does not affect this connection
        ldb2.set_dsheuristics("000000000")
        time.sleep(1)

        res = ldb2.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # Check that userPassword was not stored from ldb1
        self.assertTrue(len(res) == 1)
        self.assertFalse("userPassword" in res[0])

        m = Message()
        m.dn = Dn(ldb2, "cn=testuser,cn=users," + self.base_dn)
        m["userPassword"] = MessageElement("thatsAcomplPASS2", FLAG_MOD_REPLACE,
          "userPassword")
        ldb2.modify(m)

        res = ldb2.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # Check despite setting it with userPassword support disabled
        # on this connection it should still not be readable
        self.assertTrue(len(res) == 1)
        self.assertFalse("userPassword" in res[0])

        # Only password from ldb1 is the user's password
        creds2 = Credentials()
        creds2.set_username("testuser")
        creds2.set_password("thatsAcomplPASS1")
        creds2.set_domain(creds.get_domain())
        creds2.set_realm(creds.get_realm())
        creds2.set_workstation(creds.get_workstation())
        creds2.set_gensec_features(creds2.get_gensec_features()
                                   | gensec.FEATURE_SEAL)

        try:
            SamDB(url=host, credentials=creds2, lp=lp)
        except:
            self.fail("testuser used the wrong password")

        ldb3 = SamDB(url=host, session_info=system_session(lp),
                     credentials=creds, lp=lp)

        # Check that userPassword was stored from ldb2
        res = ldb3.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # userPassword can be read
        self.assertTrue(len(res) == 1)
        self.assertTrue("userPassword" in res[0])
        self.assertEquals(res[0]["userPassword"][0], "thatsAcomplPASS2")

        # Reset the test "dSHeuristics" (reactivate "userPassword" pwd changes)
        self.ldb.set_dsheuristics("000000001")

        ldb4 = SamDB(url=host, session_info=system_session(lp),
                     credentials=creds, lp=lp)

        # Check that userPassword that was stored from ldb2
        res = ldb4.search("cn=testuser,cn=users," + self.base_dn,
                          scope=SCOPE_BASE, attrs=["userPassword"])

        # userPassword can be not be read
        self.assertTrue(len(res) == 1)
        self.assertFalse("userPassword" in res[0])
Example #35
0
class PyCredentialsTests(TestCase):

    def setUp(self):
        super(PyCredentialsTests, self).setUp()

        self.server      = os.environ["SERVER"]
        self.domain      = os.environ["DOMAIN"]
        self.host        = os.environ["SERVER_IP"]
        self.lp          = self.get_loadparm()

        self.credentials = self.get_credentials()

        self.session     = system_session()
        self.ldb = SamDB(url="ldap://%s" % self.host,
                         session_info=self.session,
                         credentials=self.credentials,
                         lp=self.lp)

        self.create_machine_account()
        self.create_user_account()


    def tearDown(self):
        super(PyCredentialsTests, self).tearDown()
        delete_force(self.ldb, self.machine_dn)
        delete_force(self.ldb, self.user_dn)

    # Until a successful netlogon connection has been established there will
    # not be a valid authenticator associated with the credentials
    # and new_client_authenticator should throw a ValueError
    def test_no_netlogon_connection(self):
        self.assertRaises(ValueError,
                          self.machine_creds.new_client_authenticator)

    # Once a netlogon connection has been established,
    # new_client_authenticator should return a value
    #
    def test_have_netlogon_connection(self):
        c = self.get_netlogon_connection()
        a = self.machine_creds.new_client_authenticator()
        self.assertIsNotNone(a)

    # Get an authenticator and use it on a sequence of operations requiring
    # an authenticator
    def test_client_authenticator(self):
        c = self.get_netlogon_connection()
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonSamLogonWithFlags(c, authenticator, subsequent)
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)


    def test_SamLogonEx(self):
        c = self.get_netlogon_connection()

        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds)

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0

        try:
            c.netr_LogonSamLogonEx(self.server,
                                   self.user_creds.get_workstation(),
                                   logon_level,
                                   logon,
                                   validation_level,
                                   netr_flags)
        except NTSTATUSError as e:
            enum = ctypes.c_uint32(e.args[0]).value
            if enum == ntstatus.NT_STATUS_WRONG_PASSWORD:
                self.fail("got wrong password error")
            else:
                raise

    def test_SamLogonEx_no_domain(self):
        c = self.get_netlogon_connection()

        self.user_creds.set_domain('')

        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds)

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0

        try:
            c.netr_LogonSamLogonEx(self.server,
                                   self.user_creds.get_workstation(),
                                   logon_level,
                                   logon,
                                   validation_level,
                                   netr_flags)
        except NTSTATUSError as e:
            enum = ctypes.c_uint32(e.args[0]).value
            if enum == ntstatus.NT_STATUS_WRONG_PASSWORD:
                self.fail("got wrong password error")
            else:
                self.fail("got unexpected error" + str(e))

    def test_SamLogonExNTLM(self):
        c = self.get_netlogon_connection()

        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds,
                                    flags=CLI_CRED_NTLM_AUTH)

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0

        try:
            c.netr_LogonSamLogonEx(self.server,
                                   self.user_creds.get_workstation(),
                                   logon_level,
                                   logon,
                                   validation_level,
                                   netr_flags)
        except NTSTATUSError as e:
            enum = ctypes.c_uint32(e.args[0]).value
            if enum == ntstatus.NT_STATUS_WRONG_PASSWORD:
                self.fail("got wrong password error")
            else:
                raise

    def test_SamLogonExMSCHAPv2(self):
        c = self.get_netlogon_connection()

        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds,
                                    flags=CLI_CRED_NTLM_AUTH)

        logon.identity_info.parameter_control = MSV1_0_ALLOW_MSVCHAPV2

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0

        try:
            c.netr_LogonSamLogonEx(self.server,
                                   self.user_creds.get_workstation(),
                                   logon_level,
                                   logon,
                                   validation_level,
                                   netr_flags)
        except NTSTATUSError as e:
            enum = ctypes.c_uint32(e.args[0]).value
            if enum == ntstatus.NT_STATUS_WRONG_PASSWORD:
                self.fail("got wrong password error")
            else:
                raise


    # Test Credentials.encrypt_netr_crypt_password
    # By performing a NetrServerPasswordSet2
    # And the logging on using the new password.
    def test_encrypt_netr_password(self):
        # Change the password
        self.do_Netr_ServerPasswordSet2()
        # Now use the new password to perform an operation
        srvsvc.srvsvc("ncacn_np:%s" % (self.server),
                      self.lp,
                      self.machine_creds)


   # Change the current machine account password with a
   # netr_ServerPasswordSet2 call.

    def do_Netr_ServerPasswordSet2(self):
        c = self.get_netlogon_connection()
        (authenticator, subsequent) = self.get_authenticator(c)
        PWD_LEN  = 32
        DATA_LEN = 512
        newpass = samba.generate_random_password(PWD_LEN, PWD_LEN)
        encoded = newpass.encode('utf-16-le')
        pwd_len = len(encoded)
        filler  = [ord(x) for x in os.urandom(DATA_LEN-pwd_len)]
        pwd = netlogon.netr_CryptPassword()
        pwd.length = pwd_len
        pwd.data = filler + [ord(x) for x in encoded]
        self.machine_creds.encrypt_netr_crypt_password(pwd)
        c.netr_ServerPasswordSet2(self.server,
                                  self.machine_creds.get_workstation(),
                                  SEC_CHAN_WKSTA,
                                  self.machine_name,
                                  authenticator,
                                  pwd)

        self.machine_pass = newpass
        self.machine_creds.set_password(newpass)

    # Establish sealed schannel netlogon connection over TCP/IP
    #
    def get_netlogon_connection(self):
        return netlogon.netlogon("ncacn_ip_tcp:%s[schannel,seal]" % self.server,
                                 self.lp,
                                 self.machine_creds)

    #
    # Create the machine account
    def create_machine_account(self):
        self.machine_pass = samba.generate_random_password(32, 32)
        self.machine_name = MACHINE_NAME
        self.machine_dn = "cn=%s,%s" % (self.machine_name, self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, self.machine_dn)

        utf16pw = unicode(
            '"' + self.machine_pass.encode('utf-8') + '"', 'utf-8'
        ).encode('utf-16-le')
        self.ldb.add({
            "dn": self.machine_dn,
            "objectclass": "computer",
            "sAMAccountName": "%s$" % self.machine_name,
            "userAccountControl":
                str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
            "unicodePwd": utf16pw})

        self.machine_creds = Credentials()
        self.machine_creds.guess(self.get_loadparm())
        self.machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
        self.machine_creds.set_kerberos_state(DONT_USE_KERBEROS)
        self.machine_creds.set_password(self.machine_pass)
        self.machine_creds.set_username(self.machine_name + "$")
        self.machine_creds.set_workstation(self.machine_name)

    #
    # Create a test user account
    def create_user_account(self):
        self.user_pass = samba.generate_random_password(32, 32)
        self.user_name = USER_NAME
        self.user_dn = "cn=%s,%s" % (self.user_name, self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, self.user_dn)

        utf16pw = unicode(
            '"' + self.user_pass.encode('utf-8') + '"', 'utf-8'
        ).encode('utf-16-le')
        self.ldb.add({
            "dn": self.user_dn,
            "objectclass": "user",
            "sAMAccountName": "%s" % self.user_name,
            "userAccountControl": str(UF_NORMAL_ACCOUNT),
            "unicodePwd": utf16pw})

        self.user_creds = Credentials()
        self.user_creds.guess(self.get_loadparm())
        self.user_creds.set_password(self.user_pass)
        self.user_creds.set_username(self.user_name)
        self.user_creds.set_workstation(self.machine_name)
        pass

    #
    # Get the authenticator from the machine creds.
    def get_authenticator(self, c):
        auth = self.machine_creds.new_client_authenticator();
        current  = netr_Authenticator()
        current.cred.data = [ord(x) for x in auth["credential"]]
        current.timestamp = auth["timestamp"]

        subsequent = netr_Authenticator()
        return (current, subsequent)

    def do_NetrLogonSamLogonWithFlags(self, c, current, subsequent):
        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds)

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0
        c.netr_LogonSamLogonWithFlags(self.server,
                                      self.user_creds.get_workstation(),
                                      current,
                                      subsequent,
                                      logon_level,
                                      logon,
                                      validation_level,
                                      netr_flags)

    def do_NetrLogonGetDomainInfo(self, c, current, subsequent):
        query = netr_WorkstationInformation()

        c.netr_LogonGetDomainInfo(self.server,
                                  self.user_creds.get_workstation(),
                                  current,
                                  subsequent,
                                  2,
                                  query)
Example #36
0
class RodcCmdTestCase(SambaToolCmdTest):
    def setUp(self):
        super(RodcCmdTestCase, self).setUp()
        self.lp = samba.param.LoadParm()
        self.lp.load(os.environ["SMB_CONF_PATH"])
        self.creds = Credentials()
        self.creds.set_username(os.environ["DC_USERNAME"])
        self.creds.set_password(os.environ["DC_PASSWORD"])
        self.creds.guess(self.lp)
        self.session = system_session()
        self.ldb = SamDB("ldap://" + os.environ["DC_SERVER"],
            session_info=self.session, credentials=self.creds,lp=self.lp)

        self.base_dn = self.ldb.domain_dn()

        self.ldb.newuser("sambatool1", "1qazXSW@")
        self.ldb.newuser("sambatool2", "2wsxCDE#")
        self.ldb.newuser("sambatool3", "3edcVFR$")
        self.ldb.newuser("sambatool4", "4rfvBGT%")
        self.ldb.newuser("sambatool5", "5tjbNHY*")
        self.ldb.newuser("sambatool6", "6yknMJU*")

        self.ldb.add_remove_group_members("Allowed RODC Password Replication Group",
                                          ["sambatool1", "sambatool2", "sambatool3",
                                           "sambatool4", "sambatool5"],
                                          add_members_operation=True)

    def tearDown(self):
        super(RodcCmdTestCase, self).tearDown()
        self.ldb.deleteuser("sambatool1")
        self.ldb.deleteuser("sambatool2")
        self.ldb.deleteuser("sambatool3")
        self.ldb.deleteuser("sambatool4")
        self.ldb.deleteuser("sambatool5")
        self.ldb.deleteuser("sambatool6")
        (result, out, err) = self.runsubcmd("drs", "replicate", "--local", "unused",
                                            os.environ["DC_SERVER"], self.base_dn)


    def test_single_by_account_name(self):
        (result, out, err) = self.runsubcmd("rodc", "preload", "sambatool1",
                                            "--server", os.environ["DC_SERVER"])
        self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
        self.assertEqual(out, "Replicating DN CN=sambatool1,CN=Users,%s\n" % self.base_dn)
        self.assertEqual(err, "")

    def test_single_by_dn(self):
        (result, out, err) = self.runsubcmd("rodc", "preload", "cn=sambatool2,cn=users,%s" % self.base_dn,
                                            "--server", os.environ["DC_SERVER"])
        self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
        self.assertEqual(out, "Replicating DN CN=sambatool2,CN=Users,%s\n" % self.base_dn)

    def test_multi_by_account_name(self):
        (result, out, err) = self.runsubcmd("rodc", "preload", "sambatool1", "sambatool2",
                                            "--server", os.environ["DC_SERVER"])
        self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
        self.assertEqual(out, "Replicating DN CN=sambatool1,CN=Users,%s\nReplicating DN CN=sambatool2,CN=Users,%s\n" % (self.base_dn, self.base_dn))

    def test_multi_by_dn(self):
        (result, out, err) = self.runsubcmd("rodc", "preload", "cn=sambatool3,cn=users,%s" % self.base_dn, "cn=sambatool4,cn=users,%s" % self.base_dn,
                                            "--server", os.environ["DC_SERVER"])
        self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
        self.assertEqual(out, "Replicating DN CN=sambatool3,CN=Users,%s\nReplicating DN CN=sambatool4,CN=Users,%s\n" % (self.base_dn, self.base_dn))

    def test_multi_in_file(self):
        tempf = os.path.join(self.tempdir, "accountlist")
        open(tempf, 'w').write("sambatool1\nsambatool2")
        (result, out, err) = self.runsubcmd("rodc", "preload", "--file", tempf,
                                            "--server", os.environ["DC_SERVER"])
        self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
        self.assertEqual(out, "Replicating DN CN=sambatool1,CN=Users,%s\nReplicating DN CN=sambatool2,CN=Users,%s\n" % (self.base_dn, self.base_dn))
        os.unlink(tempf)

    def test_multi_with_missing_name_success(self):
        (result, out, err) = self.runsubcmd("rodc", "preload",
                                            "nonexistentuser1", "sambatool5",
                                            "nonexistentuser2",
                                            "--server", os.environ["DC_SERVER"],
                                            "--ignore-errors")
        self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
        self.assertTrue(out.startswith("Replicating DN CN=sambatool5,CN=Users,%s\n"
                                       % self.base_dn))

    def test_multi_with_missing_name_failure(self):
        (result, out, err) = self.runsubcmd("rodc", "preload",
                                            "nonexistentuser1", "sambatool5",
                                            "nonexistentuser2",
                                            "--server", os.environ["DC_SERVER"])
        self.assertCmdFail(result, "ensuring rodc prefetch quit on missing user")

    def test_multi_without_group_success(self):
        (result, out, err) = self.runsubcmd("rodc", "preload",
                                            "sambatool6", "sambatool5",
                                            "--server", os.environ["DC_SERVER"],
                                            "--ignore-errors")
        self.assertCmdSuccess(result, out, err, "ensuring rodc prefetch ran successfully")
        self.assertTrue(out.startswith("Replicating DN CN=sambatool6,CN=Users,%s\n"
                                       "Replicating DN CN=sambatool5,CN=Users,%s\n"
                                       % (self.base_dn, self.base_dn)))

    def test_multi_without_group_failure(self):
        (result, out, err) = self.runsubcmd("rodc", "preload",
                                            "sambatool6", "sambatool5",
                                            "--server", os.environ["DC_SERVER"])
        self.assertCmdFail(result, "ensuring rodc prefetch quit on non-replicated user")
Example #37
0
    def join_replicate(ctx):
        """Replicate the SAM."""

        print "Starting replication"
        ctx.local_samdb.transaction_start()
        try:
            source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
            if ctx.ntds_guid is None:
                print("Using DS_BIND_GUID_W2K3")
                destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
            else:
                destination_dsa_guid = ctx.ntds_guid

            if ctx.RODC:
                repl_creds = Credentials()
                repl_creds.guess(ctx.lp)
                repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
                repl_creds.set_username(ctx.samname)
                repl_creds.set_password(ctx.acct_pass)
            else:
                repl_creds = ctx.creds

            binding_options = "seal"
            if int(ctx.lp.get("log level")) >= 5:
                binding_options += ",print"
            repl = drs_utils.drs_Replicate(
                "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
                ctx.lp, repl_creds, ctx.local_samdb)

            repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
                    destination_dsa_guid, schema=True, rodc=ctx.RODC,
                    replica_flags=ctx.replica_flags)
            repl.replicate(ctx.config_dn, source_dsa_invocation_id,
                    destination_dsa_guid, rodc=ctx.RODC,
                    replica_flags=ctx.replica_flags)
            if not ctx.subdomain:
                # Replicate first the critical object for the basedn
                if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
                    print "Replicating critical objects from the base DN of the domain"
                    ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
                    repl.replicate(ctx.base_dn, source_dsa_invocation_id,
                                destination_dsa_guid, rodc=ctx.RODC,
                                replica_flags=ctx.domain_replica_flags)
                    ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
                else:
                    ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
                repl.replicate(ctx.base_dn, source_dsa_invocation_id,
                               destination_dsa_guid, rodc=ctx.RODC,
                               replica_flags=ctx.domain_replica_flags)
            print "Done with always replicated NC (base, config, schema)"

            for nc in (ctx.domaindns_zone, ctx.forestdns_zone):
                if nc in ctx.nc_list:
                    print "Replicating %s" % (str(nc))
                    repl.replicate(nc, source_dsa_invocation_id,
                                    destination_dsa_guid, rodc=ctx.RODC,
                                    replica_flags=ctx.replica_flags)

            if 'DC=ForestDnsZones,%s' % ctx.root_dn in ctx.nc_list:
                repl.replicate('DC=ForestDnsZones,%s' % ctx.root_dn, source_dsa_invocation_id,
                               destination_dsa_guid, rodc=ctx.RODC,
                               replica_flags=ctx.replica_flags)
            # FIXME At this point we should add an entry in the forestdns and domaindns NC
            # (those under CN=Partions,DC=...)
            # in order to indicate that we hold a replica for this NC

            if ctx.RODC:
                repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
                        destination_dsa_guid,
                        exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
                repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
                        destination_dsa_guid,
                        exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
            ctx.repl = repl
            ctx.source_dsa_invocation_id = source_dsa_invocation_id
            ctx.destination_dsa_guid = destination_dsa_guid

            print "Committing SAM database"
        except:
            ctx.local_samdb.transaction_cancel()
            raise
        else:
            ctx.local_samdb.transaction_commit()
class BasePasswordTestCase(PasswordTestCase):
    def _open_samr_user(self, res):
        self.assertTrue("objectSid" in res[0])

        (domain_sid, rid) = ndr_unpack(security.dom_sid, res[0]["objectSid"][0]).split()
        self.assertEquals(self.domain_sid, domain_sid)

        return self.samr.OpenUser(self.samr_domain, security.SEC_FLAG_MAXIMUM_ALLOWED, rid)

    def _check_attribute(self, res, name, value):
        if value is None:
            self.assertTrue(name not in res[0],
                            msg="attr[%s]=%r on dn[%s]" %
                            (name, res[0], res[0].dn))
            return

        if isinstance(value, tuple):
            (mode, value) = value
        else:
            mode = "equal"

        if mode == "ignore":
            return

        if mode == "absent":
            self.assertFalse(name in res[0],
                            msg="attr[%s] not missing on dn[%s]" %
                            (name, res[0].dn))
            return

        self.assertTrue(name in res[0],
                        msg="attr[%s] missing on dn[%s]" %
                        (name, res[0].dn))
        self.assertTrue(len(res[0][name]) == 1,
                        msg="attr[%s]=%r on dn[%s]" %
                        (name, res[0][name], res[0].dn))


        print("%s = '%s'" % (name, res[0][name][0]))

        if mode == "present":
            return

        if mode == "equal":
            v = int(res[0][name][0])
            value = int(value)
            msg = ("attr[%s]=[%s] != [%s] on dn[%s]\n"
                   "(diff %d; actual value is %s than expected)"  %
                   (name, v, value, res[0].dn, v - value,
                    ('less' if v < value else 'greater')))

            self.assertTrue(v == value, msg)
            return

        if mode == "greater":
            v = int(res[0][name][0])
            self.assertTrue(v > int(value),
                            msg="attr[%s]=[%s] <= [%s] on dn[%s] (diff %d)" %
                            (name, v, int(value), res[0].dn, v - int(value)))
            return
        if mode == "less":
            v = int(res[0][name][0])
            self.assertTrue(v < int(value),
                            msg="attr[%s]=[%s] >= [%s] on dn[%s] (diff %d)" %
                            (name, v, int(value), res[0].dn, v - int(value)))
            return
        self.assertEqual(mode, not mode, "Invalid Mode[%s]" % mode)

    def _check_account_initial(self, userdn):
        self._check_account(userdn,
                            badPwdCount=0,
                            badPasswordTime=0,
                            logonCount=0,
                            lastLogon=0,
                            lastLogonTimestamp=("absent", None),
                            userAccountControl=
                            dsdb.UF_NORMAL_ACCOUNT,
                            msDSUserAccountControlComputed=0)

    def _check_account(self, dn,
                       badPwdCount=None,
                       badPasswordTime=None,
                       logonCount=None,
                       lastLogon=None,
                       lastLogonTimestamp=None,
                       lockoutTime=None,
                       userAccountControl=None,
                       msDSUserAccountControlComputed=None,
                       effective_bad_password_count=None,
                       msg=None,
                       badPwdCountOnly=False):
        print('-=' * 36)
        if msg is not None:
            print("\033[01;32m %s \033[00m\n" % msg)
        attrs = [
           "objectSid",
           "badPwdCount",
           "badPasswordTime",
           "lastLogon",
           "lastLogonTimestamp",
           "logonCount",
           "lockoutTime",
           "userAccountControl",
           "msDS-User-Account-Control-Computed"
        ]

        # in order to prevent some time resolution problems we sleep for
        # 10 micro second
        time.sleep(0.01)

        res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs)
        self.assertTrue(len(res) == 1)
        self._check_attribute(res, "badPwdCount", badPwdCount)
        self._check_attribute(res, "lockoutTime", lockoutTime)
        self._check_attribute(res, "badPasswordTime", badPasswordTime)
        if not badPwdCountOnly:
            self._check_attribute(res, "logonCount", logonCount)
            self._check_attribute(res, "lastLogon", lastLogon)
            self._check_attribute(res, "lastLogonTimestamp", lastLogonTimestamp)
            self._check_attribute(res, "userAccountControl", userAccountControl)
            self._check_attribute(res, "msDS-User-Account-Control-Computed",
                                  msDSUserAccountControlComputed)

            lastLogon = int(res[0]["lastLogon"][0])
            logonCount = int(res[0]["logonCount"][0])

        samr_user = self._open_samr_user(res)
        uinfo3 = self.samr.QueryUserInfo(samr_user, 3)
        uinfo5 = self.samr.QueryUserInfo(samr_user, 5)
        uinfo16 = self.samr.QueryUserInfo(samr_user, 16)
        uinfo21 = self.samr.QueryUserInfo(samr_user, 21)
        self.samr.Close(samr_user)

        expected_acb_info = 0
        if not badPwdCountOnly:
            if userAccountControl & dsdb.UF_NORMAL_ACCOUNT:
                expected_acb_info |= samr.ACB_NORMAL
            if userAccountControl & dsdb.UF_ACCOUNTDISABLE:
                expected_acb_info |= samr.ACB_DISABLED
            if userAccountControl & dsdb.UF_PASSWD_NOTREQD:
                expected_acb_info |= samr.ACB_PWNOTREQ
            if msDSUserAccountControlComputed & dsdb.UF_LOCKOUT:
                expected_acb_info |= samr.ACB_AUTOLOCK
            if msDSUserAccountControlComputed & dsdb.UF_PASSWORD_EXPIRED:
                expected_acb_info |= samr.ACB_PW_EXPIRED

            self.assertEquals(uinfo3.acct_flags, expected_acb_info)
            self.assertEquals(uinfo3.last_logon, lastLogon)
            self.assertEquals(uinfo3.logon_count, logonCount)

        expected_bad_password_count = 0
        if badPwdCount is not None:
            expected_bad_password_count = badPwdCount
        if effective_bad_password_count is None:
            effective_bad_password_count = expected_bad_password_count

        self.assertEquals(uinfo3.bad_password_count, expected_bad_password_count)

        if not badPwdCountOnly:
            self.assertEquals(uinfo5.acct_flags, expected_acb_info)
            self.assertEquals(uinfo5.bad_password_count, effective_bad_password_count)
            self.assertEquals(uinfo5.last_logon, lastLogon)
            self.assertEquals(uinfo5.logon_count, logonCount)

            self.assertEquals(uinfo16.acct_flags, expected_acb_info)

            self.assertEquals(uinfo21.acct_flags, expected_acb_info)
            self.assertEquals(uinfo21.bad_password_count, effective_bad_password_count)
            self.assertEquals(uinfo21.last_logon, lastLogon)
            self.assertEquals(uinfo21.logon_count, logonCount)


        # check LDAP again and make sure the samr.QueryUserInfo
        # doesn't have any impact.
        res2 = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs)
        self.assertEquals(res[0], res2[0])

        # in order to prevent some time resolution problems we sleep for
        # 10 micro second
        time.sleep(0.01)
        return res

    def update_lockout_settings(self, threshold, duration, observation_window):
        """Updates the global user lockout settings"""
        m = Message()
        m.dn = Dn(self.ldb, self.base_dn)
        account_lockout_duration_ticks = -int(duration * (1e7))
        m["lockoutDuration"] = MessageElement(str(account_lockout_duration_ticks),
                                              FLAG_MOD_REPLACE, "lockoutDuration")
        m["lockoutThreshold"] = MessageElement(str(threshold),
                                               FLAG_MOD_REPLACE, "lockoutThreshold")
        lockout_observation_window_ticks = -int(observation_window * (1e7))
        m["lockOutObservationWindow"] = MessageElement(str(lockout_observation_window_ticks),
                                                       FLAG_MOD_REPLACE, "lockOutObservationWindow")
        self.ldb.modify(m)

    def _readd_user(self, creds, lockOutObservationWindow=0):
        username = creds.get_username()
        userpass = creds.get_password()
        userdn = "cn=%s,cn=users,%s" % (username, self.base_dn)

        delete_force(self.ldb, userdn)
        self.ldb.add({
             "dn": userdn,
             "objectclass": "user",
             "sAMAccountName": username})

        self.addCleanup(delete_force, self.ldb, userdn)

        # Sets the initial user password with a "special" password change
        # I think that this internally is a password set operation and it can
        # only be performed by someone which has password set privileges on the
        # account (at least in s4 we do handle it like that).
        self.ldb.modify_ldif("""
dn: """ + userdn + """
changetype: modify
delete: userPassword
add: userPassword
userPassword: """ + userpass + """
""")
        # Enables the user account
        self.ldb.enable_account("(sAMAccountName=%s)" % username)

        use_kerberos = creds.get_kerberos_state()
        fail_creds = self.insta_creds(self.template_creds,
                                      username=username,
                                      userpass=userpass+"X",
                                      kerberos_state=use_kerberos)
        self._check_account_initial(userdn)

        # Fail once to get a badPasswordTime
        try:
            ldb = SamDB(url=self.host_url, credentials=fail_creds, lp=self.lp)
            self.fail()
        except LdbError as e:
            (num, msg) = e.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        # Succeed to reset everything to 0
        ldb = SamDB(url=self.host_url, credentials=creds, lp=self.lp)

        return ldb

    def assertLoginFailure(self, url, creds, lp, errno=ERR_INVALID_CREDENTIALS):
        try:
            ldb = SamDB(url=url, credentials=creds, lp=lp)
            self.fail("Login unexpectedly succeeded")
        except LdbError as e1:
            (num, msg) = e1.args
            if errno is not None:
                self.assertEquals(num, errno, ("Login failed in the wrong way"
                                               "(got err %d, expected %d)" %
                                               (num, errno)))

    def setUp(self):
        super(BasePasswordTestCase, self).setUp()

        self.global_creds.set_gensec_features(self.global_creds.get_gensec_features() |
                                              gensec.FEATURE_SEAL)

        self.template_creds = Credentials()
        self.template_creds.set_username("testuser")
        self.template_creds.set_password("thatsAcomplPASS1")
        self.template_creds.set_domain(self.global_creds.get_domain())
        self.template_creds.set_realm(self.global_creds.get_realm())
        self.template_creds.set_workstation(self.global_creds.get_workstation())
        self.template_creds.set_gensec_features(self.global_creds.get_gensec_features())
        self.template_creds.set_kerberos_state(self.global_creds.get_kerberos_state())

        # Gets back the basedn
        base_dn = self.ldb.domain_dn()

        # Gets back the configuration basedn
        configuration_dn = self.ldb.get_config_basedn().get_linearized()

        res = self.ldb.search(base_dn,
                         scope=SCOPE_BASE, attrs=["lockoutDuration", "lockOutObservationWindow", "lockoutThreshold"])

        if "lockoutDuration" in res[0]:
            lockoutDuration = res[0]["lockoutDuration"][0]
        else:
            lockoutDuration = 0

        if "lockoutObservationWindow" in res[0]:
            lockoutObservationWindow = res[0]["lockoutObservationWindow"][0]
        else:
            lockoutObservationWindow = 0

        if "lockoutThreshold" in res[0]:
            lockoutThreshold = res[0]["lockoutThreshold"][0]
        else:
            lockoutTreshold = 0

        self.addCleanup(self.ldb.modify_ldif, """
dn: """ + base_dn + """
changetype: modify
replace: lockoutDuration
lockoutDuration: """ + str(lockoutDuration) + """
replace: lockoutObservationWindow
lockoutObservationWindow: """ + str(lockoutObservationWindow) + """
replace: lockoutThreshold
lockoutThreshold: """ + str(lockoutThreshold) + """
""")

        self.base_dn = self.ldb.domain_dn()
        self.account_lockout_duration = 2
        self.lockout_observation_window = 2
        self.update_lockout_settings(threshold=3, duration=2,
                                     observation_window=2)

        # update DC to allow password changes for the duration of this test
        self.allow_password_changes()

        self.domain_sid = security.dom_sid(self.ldb.get_domain_sid())
        self.samr = samr.samr("ncacn_ip_tcp:%s[seal]" % self.host, self.lp, self.global_creds)
        self.samr_handle = self.samr.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED)
        self.samr_domain = self.samr.OpenDomain(self.samr_handle, security.SEC_FLAG_MAXIMUM_ALLOWED, self.domain_sid)

        self.addCleanup(self.delete_ldb_connections)

        # (Re)adds the test user accounts
        self.lockout1krb5_creds = self.insta_creds(self.template_creds,
                                                   username="******",
                                                   userpass="******",
                                                   kerberos_state=MUST_USE_KERBEROS)
        self.lockout1krb5_ldb = self._readd_user(self.lockout1krb5_creds)
        self.lockout1ntlm_creds = self.insta_creds(self.template_creds,
                                                   username="******",
                                                   userpass="******",
                                                   kerberos_state=DONT_USE_KERBEROS)
        self.lockout1ntlm_ldb = self._readd_user(self.lockout1ntlm_creds)

    def delete_ldb_connections(self):
        del self.lockout1krb5_ldb
        del self.lockout1ntlm_ldb
        del self.ldb

    def tearDown(self):
        super(BasePasswordTestCase, self).tearDown()

    def _test_login_lockout(self, creds):
        username = creds.get_username()
        userpass = creds.get_password()
        userdn = "cn=%s,cn=users,%s" % (username, self.base_dn)

        use_kerberos = creds.get_kerberos_state()
        # This unlocks by waiting for account_lockout_duration
        if use_kerberos == MUST_USE_KERBEROS:
            logoncount_relation = 'greater'
            lastlogon_relation = 'greater'
            print("Performs a lockout attempt against LDAP using Kerberos")
        else:
            logoncount_relation = 'equal'
            lastlogon_relation = 'equal'
            print("Performs a lockout attempt against LDAP using NTLM")

        # Change password on a connection as another user
        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=("greater", 0),
                                  logonCount=(logoncount_relation, 0),
                                  lastLogon=("greater", 0),
                                  lastLogonTimestamp=("greater", 0),
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])
        logonCount = int(res[0]["logonCount"][0])
        lastLogon = int(res[0]["lastLogon"][0])
        firstLogon = lastLogon
        lastLogonTimestamp = int(res[0]["lastLogonTimestamp"][0])
        print(firstLogon)
        print(lastLogonTimestamp)


        self.assertGreater(lastLogon, badPasswordTime)
        self.assertGreaterEqual(lastLogon, lastLogonTimestamp)

        # Open a second LDB connection with the user credentials. Use the
        # command line credentials for informations like the domain, the realm
        # and the workstation.
        creds_lockout = self.insta_creds(creds)

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")

        self.assertLoginFailure(self.host_url, creds_lockout, self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=1,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0,
                                  msg='lastlogontimestamp with wrong password')
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        # Correct old password
        creds_lockout.set_password(userpass)

        ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)

        # lastLogonTimestamp should not change
        # lastLogon increases if badPwdCount is non-zero (!)
        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lastLogon=('greater', lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0,
                                  msg='LLTimestamp is updated to lastlogon')

        logonCount = int(res[0]["logonCount"][0])
        lastLogon = int(res[0]["lastLogon"][0])
        self.assertGreater(lastLogon, badPasswordTime)
        self.assertGreaterEqual(lastLogon, lastLogonTimestamp)

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")

        self.assertLoginFailure(self.host_url, creds_lockout, self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=1,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")

        try:
            ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)
            self.fail()

        except LdbError as e2:
            (num, msg) = e2.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=2,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        print("two failed password change")

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")

        try:
            ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)
            self.fail()

        except LdbError as e3:
            (num, msg) = e3.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=3,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  lockoutTime=("greater", badPasswordTime),
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=dsdb.UF_LOCKOUT)
        badPasswordTime = int(res[0]["badPasswordTime"][0])
        lockoutTime = int(res[0]["lockoutTime"][0])

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)
            self.fail()
        except LdbError as e4:
            (num, msg) = e4.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=3,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  lockoutTime=lockoutTime,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=dsdb.UF_LOCKOUT)

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)
            self.fail()
        except LdbError as e5:
            (num, msg) = e5.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=3,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  lockoutTime=lockoutTime,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=dsdb.UF_LOCKOUT)

        # The correct password, but we are locked out
        creds_lockout.set_password(userpass)
        try:
            ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)
            self.fail()
        except LdbError as e6:
            (num, msg) = e6.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=3,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  lockoutTime=lockoutTime,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=dsdb.UF_LOCKOUT)

        # wait for the lockout to end
        time.sleep(self.account_lockout_duration + 1)
        print(self.account_lockout_duration + 1)

        res = self._check_account(userdn,
                                  badPwdCount=3, effective_bad_password_count=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=logonCount,
                                  lockoutTime=lockoutTime,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)

        # The correct password after letting the timeout expire

        creds_lockout.set_password(userpass)

        creds_lockout2 = self.insta_creds(creds_lockout)

        ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout2, lp=self.lp)
        time.sleep(3)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lastLogon=(lastlogon_relation, lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  lockoutTime=0,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0,
                                  msg="lastLogon is way off")

        logonCount = int(res[0]["logonCount"][0])
        lastLogon = int(res[0]["lastLogon"][0])

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)
            self.fail()
        except LdbError as e7:
            (num, msg) = e7.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=1,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lockoutTime=0,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)
            self.fail()
        except LdbError as e8:
            (num, msg) = e8.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=2,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lockoutTime=0,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        time.sleep(self.lockout_observation_window + 1)

        res = self._check_account(userdn,
                                  badPwdCount=2, effective_bad_password_count=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=logonCount,
                                  lockoutTime=0,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)
            self.fail()
        except LdbError as e9:
            (num, msg) = e9.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=1,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lockoutTime=0,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        # The correct password without letting the timeout expire
        creds_lockout.set_password(userpass)
        ldb_lockout = SamDB(url=self.host_url, credentials=creds_lockout, lp=self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lockoutTime=0,
                                  lastLogon=("greater", lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)

    def _test_multiple_logon(self, creds):
        # Test the happy case in which a user logs on correctly, then
        # logs on correctly again, so that the bad password and
        # lockout times are both zero the second time. The lastlogon
        # time should increase.

        # Open a second LDB connection with the user credentials. Use the
        # command line credentials for informations like the domain, the realm
        # and the workstation.
        username = creds.get_username()
        userdn = "cn=%s,cn=users,%s" % (username, self.base_dn)

        use_kerberos = creds.get_kerberos_state()
        if use_kerberos == MUST_USE_KERBEROS:
            print("Testing multiple logon with Kerberos")
            logoncount_relation = 'greater'
            lastlogon_relation = 'greater'
        else:
            print("Testing multiple logon with NTLM")
            logoncount_relation = 'equal'
            lastlogon_relation = 'equal'

        SamDB(url=self.host_url, credentials=self.insta_creds(creds), lp=self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=("greater", 0),
                                  logonCount=(logoncount_relation, 0),
                                  lastLogon=("greater", 0),
                                  lastLogonTimestamp=("greater", 0),
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])
        logonCount = int(res[0]["logonCount"][0])
        lastLogon = int(res[0]["lastLogon"][0])
        lastLogonTimestamp = int(res[0]["lastLogonTimestamp"][0])
        firstLogon = lastLogon
        print("last logon is %d" % lastLogon)
        self.assertGreater(lastLogon, badPasswordTime)
        self.assertGreaterEqual(lastLogon, lastLogonTimestamp)

        time.sleep(1)
        SamDB(url=self.host_url, credentials=self.insta_creds(creds), lp=self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lastLogon=(lastlogon_relation, lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                  dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0,
                                  msg=("second logon, firstlogon was %s" %
                                       firstLogon))


        lastLogon = int(res[0]["lastLogon"][0])

        time.sleep(1)

        SamDB(url=self.host_url, credentials=self.insta_creds(creds), lp=self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lastLogon=(lastlogon_relation, lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=
                                    dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
Example #39
0
class LDAPBackend(ProvisionBackend):

    def __init__(self, backend_type, paths=None, lp=None,
                 names=None, logger=None, domainsid=None,
                 schema=None, hostname=None, ldapadminpass=None,
                 slapd_path=None, ldap_backend_extra_port=None,
                 ldap_backend_forced_uri=None, ldap_dryrun_mode=False):

        super(LDAPBackend, self).__init__(backend_type=backend_type,
                paths=paths, lp=lp,
                names=names, logger=logger)

        self.domainsid = domainsid
        self.schema = schema
        self.hostname = hostname

        self.ldapdir = os.path.join(paths.private_dir, "ldap")
        self.ldapadminpass = ldapadminpass

        self.slapd_path = slapd_path
        self.slapd_command = None
        self.slapd_command_escaped = None
        self.slapd_pid = os.path.join(self.ldapdir, "slapd.pid")

        self.ldap_backend_extra_port = ldap_backend_extra_port
        self.ldap_dryrun_mode = ldap_dryrun_mode

        if ldap_backend_forced_uri is not None:
            self.ldap_uri = ldap_backend_forced_uri
        else:
            self.ldap_uri = "ldapi://%s" % urllib_quote(
                os.path.join(self.ldapdir, "ldapi"), safe="")

        if not os.path.exists(self.ldapdir):
            os.mkdir(self.ldapdir)

    def init(self):
        from samba.provision import ProvisioningError
        # we will shortly start slapd with ldapi for final provisioning. first
        # check with ldapsearch -> rootDSE via self.ldap_uri if another
        # instance of slapd is already running
        try:
            ldapi_db = Ldb(self.ldap_uri)
            ldapi_db.search(base="", scope=SCOPE_BASE,
                expression="(objectClass=OpenLDAProotDSE)")
            try:
                f = open(self.slapd_pid, "r")
            except IOError as err:
                if err != errno.ENOENT:
                    raise
            else:
                try:
                    p = f.read()
                finally:
                    f.close()
                self.logger.info("Check for slapd process with PID: %s and terminate it manually." % p)
            raise SlapdAlreadyRunning(self.ldap_uri)
        except LdbError:
            # XXX: We should never be catching all Ldb errors
            pass

        # Try to print helpful messages when the user has not specified the
        # path to slapd
        if self.slapd_path is None:
            raise ProvisioningError("Warning: LDAP-Backend must be setup with path to slapd, e.g. --slapd-path=\"/usr/local/libexec/slapd\"!")
        if not os.path.exists(self.slapd_path):
            self.logger.warning("Path (%s) to slapd does not exist!",
                self.slapd_path)

        if not os.path.isdir(self.ldapdir):
            os.makedirs(self.ldapdir, 0o700)

        # Put the LDIF of the schema into a database so we can search on
        # it to generate schema-dependent configurations in Fedora DS and
        # OpenLDAP
        schemadb_path = os.path.join(self.ldapdir, "schema-tmp.ldb")
        try:
            os.unlink(schemadb_path)
        except OSError:
            pass

        self.schema.write_to_tmp_ldb(schemadb_path)

        self.credentials = Credentials()
        self.credentials.guess(self.lp)
        # Kerberos to an ldapi:// backend makes no sense (we also force EXTERNAL)
        self.credentials.set_kerberos_state(DONT_USE_KERBEROS)
        self.credentials.set_username("samba-admin")
        self.credentials.set_password(self.ldapadminpass)
        self.credentials.set_forced_sasl_mech("EXTERNAL")

        self.provision()

    def provision(self):
        pass

    def start(self):
        from samba.provision import ProvisioningError
        self.slapd_command_escaped = "\'" + "\' \'".join(self.slapd_command) + "\'"
        ldap_backend_script = os.path.join(self.ldapdir, "ldap_backend_startup.sh")
        f = open(ldap_backend_script, 'w')
        try:
            f.write("#!/bin/sh\n" + self.slapd_command_escaped + " $@\n")
        finally:
            f.close()

        os.chmod(ldap_backend_script, 0o755)

        # Now start the slapd, so we can provision onto it.  We keep the
        # subprocess context around, to kill this off at the successful
        # end of the script
        self.slapd = subprocess.Popen(self.slapd_provision_command,
            close_fds=True, shell=False)

        count = 0
        while self.slapd.poll() is None:
            # Wait until the socket appears
            try:
                time.sleep(1)
                ldapi_db = Ldb(self.ldap_uri, lp=self.lp, credentials=self.credentials)
                ldapi_db.search(base="", scope=SCOPE_BASE,
                    expression="(objectClass=OpenLDAProotDSE)")
                # If we have got here, then we must have a valid connection to
                # the LDAP server!
                return
            except LdbError:
                count = count + 1

                if count > 15:
                    self.logger.error("Could not connect to slapd started with: %s" %  "\'" + "\' \'".join(self.slapd_provision_command) + "\'")
                    raise ProvisioningError("slapd never accepted a connection within 15 seconds of starting")

        self.logger.error("Could not start slapd with: %s" % "\'" + "\' \'".join(self.slapd_provision_command) + "\'")
        raise ProvisioningError("slapd died before we could make a connection to it")

    def shutdown(self):
        # if an LDAP backend is in use, terminate slapd after final provision
        # and check its proper termination
        if self.slapd.poll() is None:
            # Kill the slapd
            if getattr(self.slapd, "terminate", None) is not None:
                self.slapd.terminate()
            else:
                # Older python versions don't have .terminate()
                import signal
                os.kill(self.slapd.pid, signal.SIGTERM)

            # and now wait for it to die
            self.slapd.communicate()

    def post_setup(self):
        return LDAPBackendResult(self.slapd_command_escaped,
                    self.ldapdir)
Example #40
0
class PyCredentialsTests(TestCase):

    def setUp(self):
        super(PyCredentialsTests, self).setUp()

        self.server      = os.environ["SERVER"]
        self.domain      = os.environ["DOMAIN"]
        self.host        = os.environ["SERVER_IP"]
        self.lp          = self.get_loadparm()

        self.credentials = self.get_credentials()

        self.session     = system_session()
        self.ldb = SamDB(url="ldap://%s" % self.host,
                         session_info=self.session,
                         credentials=self.credentials,
                         lp=self.lp)

        self.create_machine_account()
        self.create_user_account()

    def tearDown(self):
        super(PyCredentialsTests, self).tearDown()
        delete_force(self.ldb, self.machine_dn)
        delete_force(self.ldb, self.user_dn)

    # Until a successful netlogon connection has been established there will
    # not be a valid authenticator associated with the credentials
    # and new_client_authenticator should throw a ValueError
    def test_no_netlogon_connection(self):
        self.assertRaises(ValueError,
                          self.machine_creds.new_client_authenticator)

    # Once a netlogon connection has been established,
    # new_client_authenticator should return a value
    #
    def test_have_netlogon_connection(self):
        c = self.get_netlogon_connection()
        a = self.machine_creds.new_client_authenticator()
        self.assertIsNotNone(a)

    # Get an authenticator and use it on a sequence of operations requiring
    # an authenticator
    def test_client_authenticator(self):
        c = self.get_netlogon_connection()
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonSamLogonWithFlags(c, authenticator, subsequent)
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)

    def test_SamLogonEx(self):
        c = self.get_netlogon_connection()

        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds)

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0

        try:
            c.netr_LogonSamLogonEx(self.server,
                                   self.user_creds.get_workstation(),
                                   logon_level,
                                   logon,
                                   validation_level,
                                   netr_flags)
        except NTSTATUSError as e:
            enum = ctypes.c_uint32(e.args[0]).value
            if enum == ntstatus.NT_STATUS_WRONG_PASSWORD:
                self.fail("got wrong password error")
            else:
                raise

    def test_SamLogonEx_no_domain(self):
        c = self.get_netlogon_connection()

        self.user_creds.set_domain('')

        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds)

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0

        try:
            c.netr_LogonSamLogonEx(self.server,
                                   self.user_creds.get_workstation(),
                                   logon_level,
                                   logon,
                                   validation_level,
                                   netr_flags)
        except NTSTATUSError as e:
            enum = ctypes.c_uint32(e.args[0]).value
            if enum == ntstatus.NT_STATUS_WRONG_PASSWORD:
                self.fail("got wrong password error")
            else:
                self.fail("got unexpected error" + str(e))

    def test_SamLogonExNTLM(self):
        c = self.get_netlogon_connection()

        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds,
                                    flags=CLI_CRED_NTLM_AUTH)

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0

        try:
            c.netr_LogonSamLogonEx(self.server,
                                   self.user_creds.get_workstation(),
                                   logon_level,
                                   logon,
                                   validation_level,
                                   netr_flags)
        except NTSTATUSError as e:
            enum = ctypes.c_uint32(e.args[0]).value
            if enum == ntstatus.NT_STATUS_WRONG_PASSWORD:
                self.fail("got wrong password error")
            else:
                raise

    def test_SamLogonExMSCHAPv2(self):
        c = self.get_netlogon_connection()

        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds,
                                    flags=CLI_CRED_NTLM_AUTH)

        logon.identity_info.parameter_control = MSV1_0_ALLOW_MSVCHAPV2

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0

        try:
            c.netr_LogonSamLogonEx(self.server,
                                   self.user_creds.get_workstation(),
                                   logon_level,
                                   logon,
                                   validation_level,
                                   netr_flags)
        except NTSTATUSError as e:
            enum = ctypes.c_uint32(e.args[0]).value
            if enum == ntstatus.NT_STATUS_WRONG_PASSWORD:
                self.fail("got wrong password error")
            else:
                raise

    # Test Credentials.encrypt_netr_crypt_password
    # By performing a NetrServerPasswordSet2
    # And the logging on using the new password.

    def test_encrypt_netr_password(self):
        # Change the password
        self.do_Netr_ServerPasswordSet2()
        # Now use the new password to perform an operation
        srvsvc.srvsvc("ncacn_np:%s" % (self.server),
                      self.lp,
                      self.machine_creds)

   # Change the current machine account password with a
   # netr_ServerPasswordSet2 call.

    def do_Netr_ServerPasswordSet2(self):
        c = self.get_netlogon_connection()
        (authenticator, subsequent) = self.get_authenticator(c)
        PWD_LEN  = 32
        DATA_LEN = 512
        newpass = samba.generate_random_password(PWD_LEN, PWD_LEN)
        encoded = newpass.encode('utf-16-le')
        pwd_len = len(encoded)
        filler  = [x if isinstance(x, int) else ord(x) for x in os.urandom(DATA_LEN - pwd_len)]
        pwd = netlogon.netr_CryptPassword()
        pwd.length = pwd_len
        pwd.data = filler + [x if isinstance(x, int) else ord(x) for x in encoded]
        self.machine_creds.encrypt_netr_crypt_password(pwd)
        c.netr_ServerPasswordSet2(self.server,
                                  self.machine_creds.get_workstation(),
                                  SEC_CHAN_WKSTA,
                                  self.machine_name,
                                  authenticator,
                                  pwd)

        self.machine_pass = newpass
        self.machine_creds.set_password(newpass)

    # Establish sealed schannel netlogon connection over TCP/IP
    #
    def get_netlogon_connection(self):
        return netlogon.netlogon("ncacn_ip_tcp:%s[schannel,seal]" % self.server,
                                 self.lp,
                                 self.machine_creds)

    #
    # Create the machine account
    def create_machine_account(self):
        self.machine_pass = samba.generate_random_password(32, 32)
        self.machine_name = MACHINE_NAME
        self.machine_dn = "cn=%s,%s" % (self.machine_name, self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, self.machine_dn)

        utf16pw = ('"%s"' % get_string(self.machine_pass)).encode('utf-16-le')
        self.ldb.add({
            "dn": self.machine_dn,
            "objectclass": "computer",
            "sAMAccountName": "%s$" % self.machine_name,
            "userAccountControl":
                str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
            "unicodePwd": utf16pw})

        self.machine_creds = Credentials()
        self.machine_creds.guess(self.get_loadparm())
        self.machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
        self.machine_creds.set_kerberos_state(DONT_USE_KERBEROS)
        self.machine_creds.set_password(self.machine_pass)
        self.machine_creds.set_username(self.machine_name + "$")
        self.machine_creds.set_workstation(self.machine_name)

    #
    # Create a test user account
    def create_user_account(self):
        self.user_pass = samba.generate_random_password(32, 32)
        self.user_name = USER_NAME
        self.user_dn = "cn=%s,%s" % (self.user_name, self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, self.user_dn)

        utf16pw = ('"%s"' % get_string(self.user_pass)).encode('utf-16-le')
        self.ldb.add({
            "dn": self.user_dn,
            "objectclass": "user",
            "sAMAccountName": "%s" % self.user_name,
            "userAccountControl": str(UF_NORMAL_ACCOUNT),
            "unicodePwd": utf16pw})

        self.user_creds = Credentials()
        self.user_creds.guess(self.get_loadparm())
        self.user_creds.set_password(self.user_pass)
        self.user_creds.set_username(self.user_name)
        self.user_creds.set_workstation(self.machine_name)
        pass

    #
    # Get the authenticator from the machine creds.
    def get_authenticator(self, c):
        auth = self.machine_creds.new_client_authenticator()
        current = netr_Authenticator()
        current.cred.data = [x if isinstance(x, int) else ord(x) for x in auth["credential"]]
        current.timestamp = auth["timestamp"]

        subsequent = netr_Authenticator()
        return (current, subsequent)

    def do_NetrLogonSamLogonWithFlags(self, c, current, subsequent):
        logon = samlogon_logon_info(self.domain,
                                    self.machine_name,
                                    self.user_creds)

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0
        c.netr_LogonSamLogonWithFlags(self.server,
                                      self.user_creds.get_workstation(),
                                      current,
                                      subsequent,
                                      logon_level,
                                      logon,
                                      validation_level,
                                      netr_flags)

    def do_NetrLogonGetDomainInfo(self, c, current, subsequent):
        query = netr_WorkstationInformation()

        c.netr_LogonGetDomainInfo(self.server,
                                  self.user_creds.get_workstation(),
                                  current,
                                  subsequent,
                                  2,
                                  query)
Example #41
0
class PassWordHashLDAPTests(PassWordHashTests):

    def setUp(self):
        super(PassWordHashLDAPTests, self).setUp()

    # Get the supplemental credentials for the user under test
    def get_supplemental_creds_drs(self):
        binding_str = "ncacn_ip_tcp:%s[seal]" % os.environ["SERVER"]
        dn = "cn=" + USER_NAME + ",cn=users," + self.base_dn
        drs = drsuapi.drsuapi(binding_str, self.get_loadparm(), self.creds)
        (drs_handle, supported_extensions) = drs_utils.drs_DsBind(drs)

        req8 = drsuapi.DsGetNCChangesRequest8()

        null_guid = misc.GUID()
        req8.destination_dsa_guid          = null_guid
        req8.source_dsa_invocation_id      = null_guid
        req8.naming_context                = drsuapi.DsReplicaObjectIdentifier()
        req8.naming_context.dn             = unicode(dn)

        req8.highwatermark = drsuapi.DsReplicaHighWaterMark()
        req8.highwatermark.tmp_highest_usn = 0
        req8.highwatermark.reserved_usn    = 0
        req8.highwatermark.highest_usn     = 0
        req8.uptodateness_vector           = None
        req8.replica_flags                 = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
                                              drsuapi.DRSUAPI_DRS_PER_SYNC |
                                              drsuapi.DRSUAPI_DRS_GET_ANC |
                                              drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
                                              drsuapi.DRSUAPI_DRS_WRIT_REP)
        req8.max_object_count         = 402
        req8.max_ndr_size             = 402116
        req8.extended_op              = drsuapi.DRSUAPI_EXOP_REPL_OBJ
        req8.fsmo_info                = 0
        req8.partial_attribute_set    = None
        req8.partial_attribute_set_ex = None
        req8.mapping_ctr.num_mappings = 0
        req8.mapping_ctr.mappings     = None
        (level, ctr) = drs.DsGetNCChanges(drs_handle, 8, req8)

        obj_item = ctr.first_object
        obj = obj_item.object

        sc_blob = None

        for i in range(0, obj.attribute_ctr.num_attributes):
            attr = obj.attribute_ctr.attributes[i]
            if attid_equal(attr.attid,
                           drsuapi.DRSUAPI_ATTID_supplementalCredentials):
                net_ctx = net.Net(self.creds)
                net_ctx.replicate_decrypt(drs, attr, 0)
                sc_blob = attr.value_ctr.values[0].blob

        sc = ndr_unpack(drsblobs.supplementalCredentialsBlob, sc_blob)
        return sc

    def test_wDigest_supplementalCredentials(self):
        self.creds = Credentials()
        self.creds.set_username(os.environ["USERNAME"])
        self.creds.set_password(os.environ["PASSWORD"])
        self.creds.guess(self.lp)
        ldb = SamDB("ldap://" + os.environ["SERVER"],
                    credentials=self.creds,
                    lp=self.lp)

        self.add_user(ldb=ldb)

        sc = self.get_supplemental_creds_drs()

        (pos, package) = get_package(sc, "Primary:WDigest")
        self.assertEquals("Primary:WDigest", package.name)

        # Check that the WDigest values are correct.
        #
        digests = ndr_unpack(drsblobs.package_PrimaryWDigestBlob,
                             binascii.a2b_hex(package.data))
        self.check_wdigests(digests)
Example #42
0
class SmbCaclsBlockboxTestBase(BlackboxTestCase):

    def setUp(self):
        super(SmbCaclsBlockboxTestBase, self).setUp()
        self.lp = s3param.get_context()
        self.server = os.environ["SERVER"]
        self.user = os.environ["USER"]
        self.passwd = os.environ["PASSWORD"]
        self.creds = Credentials()
        self.creds.guess(self.lp)
        self.creds.set_username(self.user)
        self.creds.set_password(self.passwd)
        self.testdir = os.getenv("TESTDIR", "smbcacls")
        self.share = os.getenv("SHARE", "tmp")
        self.dirpath = os.path.join(os.environ["LOCAL_PATH"],self.testdir)

    def tearDown(self):
        try:
            # remote removal doesn't seem to work with dfs share(s)
            # #TODO find out if this is intentional (it very well might be)
            # so if we fail with remote remove perform local remove
            # (of remote files) instead
            smbclient_args = self.build_test_cmd("smbclient", ["//%s/%s" % (self.server, self.share), "-c", "deltree %s/*" % self.testdir])
            out = self.check_output(smbclient_args)
            if "NT_STATUS_OBJECT_PATH_NOT_FOUND" in out.decode():
                raise Exception("deltree: failed without setting errcode")
        except Exception as e:
            print("remote remove failed: %s" % str(e))
            print("falling back to removing contents of local dir: %s" % self.dirpath)
            if os.path.exists(self.dirpath):
                for entry in os.listdir(self.dirpath):
                    fullpath = os.path.join(self.dirpath, entry)
                    if os.path.isdir(fullpath):
                        import shutil
                        shutil.rmtree(fullpath)
                    else:
                        os.unlink(fullpath)

    def ace_dump(self, ace):
        for key, value in ace.items():
            print ("%s=%s," % (key, value), end="")
            print ("")

    def ace_cmp(self, left, right):
        for key, value in left.items():
            if key == "user_dom":
                continue
            if not key in right:
                print ("no entry for: %s" % key)
                return False
            if value != right[key]:
                print ("mismatch: %s:%s != %s:%s" % (key, value, key, right[key]))
                return False
        return True

    def ace_parse_str(self, ace):
        parts = ace.split(':')
        result = {}
        if parts[0] != "ACL":
            raise Exception("invalid ace string:%" % ace)
        if "\\" in parts[1]:
            result["user_dom"], result["user"] = parts[1].split("\\")
        elif "/" in parts[1]:
            result["user_dom"], result["user"] = parts[1].split("/")
        else:
            result["user"] = parts[1]
        result["type"], result["inherit"], result["permissions"] = parts[2].split('/')
        return result

    def build_test_cmd(self, cmd, args):
        cmd = [cmd, "-U%s%%%s" % (self.user, self.passwd)]
        cmd.extend(args)
        return cmd

    def smb_cacls(self, args):
        cacls_args = ["//%s/%s" % (self.server, self.share)]
        cacls_args.extend(args)
        out = self.check_output(self.build_test_cmd("smbcacls", cacls_args))
        return out

    def create_remote_test_file(self, remotepath):
        with self.mktemp() as tmpfile:
            filepath = os.path.join(self.testdir, remotepath)
            (dirpath, filename) = os.path.split(remotepath)
            remote_path = ""
            if len(dirpath):
                remote_path = self.testdir.replace("/", "\\", 10)
                for seg in dirpath.split(os.sep):
                    remote_path = remote_path + "\\" + seg
                    smbclient_args = self.build_test_cmd("smbclient", ["//%s/%s" % (self.server, self.share), "-c", "mkdir %s" % remote_path])
                    self.check_output(smbclient_args)
            smbclient_args = self.build_test_cmd("smbclient", ["//%s/%s" % (self.server, self.share), "-c", "put  %s %s" % (tmpfile, filepath)])
            out = self.check_output(smbclient_args)
        return filepath


    def file_ace_check(self, remotepath, ace):
        smbcacls_args = self.build_test_cmd("smbcacls",
                            ["//%s/%s" % (self.server, self.share), "--get",
                            remotepath])
        try:
            output = self.check_output(smbcacls_args)
        except BlackboxProcessError as e:
            print(str(e))
            return False
        out_str = output.decode()
        aces = []
        for line in out_str.split("\n"):
            if line.startswith("ACL"):
                aces.append(line)
        for acl in aces:
            acl_ace = self.ace_parse_str(acl)
            if ace["user"] == acl_ace["user"] and ace["type"] ==  acl_ace["type"]:
                print ("found ACE for %s" % acl_ace["user"])
                if not self.ace_cmp(acl_ace, ace):
                    print ("differences between file ACE: ")
                    self.ace_dump(acl_ace)
                    print ("and expected ACE: ")
                    self.ace_dump(ace)
                else:
                    print ("matched ACE for %s" % acl_ace["user"])
                    self.ace_dump(ace)
                    return True
        return False
Example #43
0
class PyKrb5CredentialsTests(TestCase):

    def setUp(self):
        super(PyKrb5CredentialsTests, self).setUp()

        self.server      = os.environ["SERVER"]
        self.domain      = os.environ["DOMAIN"]
        self.host        = os.environ["SERVER_IP"]
        self.lp          = self.get_loadparm()

        self.credentials = self.get_credentials()

        self.session     = system_session()
        self.ldb = SamDB(url="ldap://%s" % self.host,
                         session_info=self.session,
                         credentials=self.credentials,
                         lp=self.lp)

        self.create_machine_account()


    def tearDown(self):
        super(PyKrb5CredentialsTests, self).tearDown()
        delete_force(self.ldb, self.machine_dn)

    def test_get_named_ccache(self):
        name = "MEMORY:py_creds_machine"
        ccache = self.machine_creds.get_named_ccache(self.lp,
                                                     name)
        self.assertEqual(ccache.get_name(), name)

    def test_get_unnamed_ccache(self):
        ccache = self.machine_creds.get_named_ccache(self.lp)
        self.assertIsNotNone(ccache.get_name())

    def test_set_named_ccache(self):
        ccache = self.machine_creds.get_named_ccache(self.lp)

        creds = Credentials()
        creds.set_named_ccache(ccache.get_name())

        ccache2 = creds.get_named_ccache(self.lp)
        self.assertEqual(ccache.get_name(), ccache2.get_name())

    #
    # Create the machine account
    def create_machine_account(self):
        self.machine_pass = samba.generate_random_password(32, 32)
        self.machine_name = MACHINE_NAME
        self.machine_dn = "cn=%s,%s" % (self.machine_name, self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, self.machine_dn)
        # get unicode str for both py2 and py3
        pass_unicode = self.machine_pass.encode('utf-8').decode('utf-8')
        utf16pw = u'"{}"'.format(pass_unicode).encode('utf-16-le')
        self.ldb.add({
            "dn": self.machine_dn,
            "objectclass": "computer",
            "sAMAccountName": "%s$" % self.machine_name,
            "userAccountControl":
                str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
            "unicodePwd": utf16pw})

        self.machine_creds = Credentials()
        self.machine_creds.guess(self.get_loadparm())
        self.machine_creds.set_password(self.machine_pass)
        self.machine_creds.set_username(self.machine_name + "$")
        self.machine_creds.set_workstation(self.machine_name)
Example #44
0
    def setUp(self):
        super(PasswordTests, self).setUp()
        self.ldb = SamDB(url=host, session_info=system_session(lp), credentials=creds, lp=lp)

        # Gets back the basedn
        base_dn = self.ldb.domain_dn()

        # Gets back the configuration basedn
        configuration_dn = self.ldb.get_config_basedn().get_linearized()

        # permit password changes during this test
        self.allow_password_changes()

        self.base_dn = self.ldb.domain_dn()

        # (Re)adds the test user "testuser" with no password atm
        delete_force(self.ldb, "cn=testuser,cn=users," + self.base_dn)
        self.ldb.add({
             "dn": "cn=testuser,cn=users," + self.base_dn,
             "objectclass": "user",
             "sAMAccountName": "testuser"})

        # Tests a password change when we don't have any password yet with a
        # wrong old password
        try:
            self.ldb.modify_ldif("""
dn: cn=testuser,cn=users,""" + self.base_dn + """
changetype: modify
delete: userPassword
userPassword: noPassword
add: userPassword
userPassword: thatsAcomplPASS2
""")
            self.fail()
        except LdbError as e:
            (num, msg) = e.args
            self.assertEquals(num, ERR_CONSTRAINT_VIOLATION)
            # Windows (2008 at least) seems to have some small bug here: it
            # returns "0000056A" on longer (always wrong) previous passwords.
            self.assertTrue('00000056' in msg)

        # Sets the initial user password with a "special" password change
        # I think that this internally is a password set operation and it can
        # only be performed by someone which has password set privileges on the
        # account (at least in s4 we do handle it like that).
        self.ldb.modify_ldif("""
dn: cn=testuser,cn=users,""" + self.base_dn + """
changetype: modify
delete: userPassword
add: userPassword
userPassword: thatsAcomplPASS1
""")

        # But in the other way around this special syntax doesn't work
        try:
            self.ldb.modify_ldif("""
dn: cn=testuser,cn=users,""" + self.base_dn + """
changetype: modify
delete: userPassword
userPassword: thatsAcomplPASS1
add: userPassword
""")
            self.fail()
        except LdbError as e1:
            (num, _) = e1.args
            self.assertEquals(num, ERR_CONSTRAINT_VIOLATION)

        # Enables the user account
        self.ldb.enable_account("(sAMAccountName=testuser)")

        # Open a second LDB connection with the user credentials. Use the
        # command line credentials for informations like the domain, the realm
        # and the workstation.
        creds2 = Credentials()
        creds2.set_username("testuser")
        creds2.set_password("thatsAcomplPASS1")
        creds2.set_domain(creds.get_domain())
        creds2.set_realm(creds.get_realm())
        creds2.set_workstation(creds.get_workstation())
        creds2.set_gensec_features(creds2.get_gensec_features()
                                                          | gensec.FEATURE_SEAL)
        self.ldb2 = SamDB(url=host, credentials=creds2, lp=lp)
Example #45
0
    credopts.add_option('--krb5-ccache',
                        dest='krb5_ccache',
                        help='Kerberos Credentials cache')
    parser.add_option_group(credopts)

    # Set the options and the arguments
    (opts, args) = parser.parse_args()

    # Set the loadparm context
    lp = LoadParm()
    if os.getenv("SMB_CONF_PATH") is not None:
        lp.load(os.getenv("SMB_CONF_PATH"))
    else:
        lp.load_default()

    # Initialize the session
    creds = Credentials()
    if opts.username and opts.password:
        creds.set_username(opts.username)
        creds.set_password(opts.password)
    elif opts.krb5_ccache:
        creds.set_named_ccache(opts.krb5_ccache)
    creds.guess(lp)

    from dialogs import GPMC, GPME
    from yast import UISequencer
    s = UISequencer(lp, creds)
    funcs = [(lambda lp, creds: GPMC(lp, creds).Show()),
             (lambda gpo, lp, creds: GPME(gpo, lp, creds).Show())]
    s.run(funcs)
Example #46
0
class AuthLogTestsWinbind(AuthLogTestBase, BlackboxTestCase):

    #
    # Helper function to watch for authentication messages on the
    # Domain Controller.
    #
    def dc_watcher(self):

        (r1, w1) = os.pipe()
        pid = os.fork()
        if pid != 0:
            # Parent process return the result socket to the caller.
            return r1

        # Load the lp context for the Domain Controller, rather than the
        # member server.
        config_file = os.environ["DC_SERVERCONFFILE"]
        lp_ctx = LoadParm()
        lp_ctx.load(config_file)

        #
        # Is the message a SamLogon authentication?
        def is_sam_logon(m):
            if m is None:
                return False
            msg = json.loads(m)
            return (msg["type"] == "Authentication" and
                    msg["Authentication"]["serviceDescription"] == "SamLogon")

        #
        # Handler function for received authentication messages.
        def message_handler(context, msgType, src, message):
            # Print the message to help debugging the tests.
            # as it's a JSON message it does not look like a sub-unit message.
            print(message)
            self.dc_msgs.append(message)

        # Set up a messaging context to listen for authentication events on
        # the domain controller.
        msg_ctx = Messaging((1, ), lp_ctx=lp_ctx)
        msg_ctx.irpc_add_name(AUTH_EVENT_NAME)
        msg_handler_and_context = (message_handler, None)
        msg_ctx.register(msg_handler_and_context, msg_type=MSG_AUTH_LOG)

        # Wait for the SamLogon message.
        # As there could be other SamLogon's in progress we need to collect
        # all the SamLogons and let the caller match them to the session.
        self.dc_msgs = []
        start_time = time.time()
        while (time.time() - start_time < 1):
            msg_ctx.loop_once(0.1)

        # Only interested in SamLogon messages, filter out the rest
        msgs = list(filter(is_sam_logon, self.dc_msgs))
        if msgs:
            for m in msgs:
                m += "\n"
                os.write(w1, get_bytes(m))
        else:
            os.write(w1, get_bytes("None\n"))
        os.close(w1)

        msg_ctx.deregister(msg_handler_and_context, msg_type=MSG_AUTH_LOG)
        msg_ctx.irpc_remove_name(AUTH_EVENT_NAME)

        os._exit(0)

    # Remove any DCE/RPC ncacn_np messages
    # these only get triggered once per session, and stripping them out
    # avoids ordering dependencies in the tests
    #
    def filter_messages(self, messages):
        def keep(msg):
            if (msg["type"] == "Authorization"
                    and msg["Authorization"]["serviceDescription"] == "DCE/RPC"
                    and msg["Authorization"]["authType"] == "ncacn_np"):
                return False
            else:
                return True

        return list(filter(keep, messages))

    def setUp(self):
        super(AuthLogTestsWinbind, self).setUp()
        self.domain = os.environ["DOMAIN"]
        self.host = os.environ["SERVER"]
        self.dc = os.environ["DC_SERVER"]
        self.lp = self.get_loadparm()
        self.credentials = self.get_credentials()
        self.session = system_session()

        self.ldb = SamDB(url="ldap://{0}".format(self.dc),
                         session_info=self.session,
                         credentials=self.credentials,
                         lp=self.lp)
        self.create_user_account()

    def tearDown(self):
        super(AuthLogTestsWinbind, self).tearDown()
        delete_force(self.ldb, self.user_dn)

    #
    # Create a test user account
    def create_user_account(self):
        self.user_pass = self.random_password()
        self.user_name = USER_NAME
        self.user_dn = "cn=%s,%s" % (self.user_name, self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, self.user_dn)

        utf16pw = ('"%s"' % get_string(self.user_pass)).encode('utf-16-le')
        self.ldb.add({
            "dn": self.user_dn,
            "objectclass": "user",
            "sAMAccountName": "%s" % self.user_name,
            "userAccountControl": str(UF_NORMAL_ACCOUNT),
            "unicodePwd": utf16pw
        })

        self.user_creds = Credentials()
        self.user_creds.guess(self.get_loadparm())
        self.user_creds.set_password(self.user_pass)
        self.user_creds.set_username(self.user_name)
        self.user_creds.set_workstation(self.server)

    #
    # Check that the domain server received a SamLogon request for the
    # current logon.
    #
    def check_domain_server_authentication(self, pipe, logon_id, description):

        messages = os.read(pipe, 8192)
        messages = get_string(messages)
        if len(messages) == 0 or messages == "None":
            self.fail("No Domain server authentication message")

        #
        # Look for the SamLogon request matching logon_id
        msg = None
        for message in messages.split("\n"):
            msg = json.loads(get_string(message))
            if logon_id == msg["Authentication"]["logonId"]:
                break
            msg = None

        if msg is None:
            self.fail("No Domain server authentication message")

        #
        # Validate that message contains the expected data
        #
        self.assertEquals("Authentication", msg["type"])
        self.assertEquals(logon_id, msg["Authentication"]["logonId"])
        self.assertEquals("SamLogon",
                          msg["Authentication"]["serviceDescription"])
        self.assertEquals(description,
                          msg["Authentication"]["authDescription"])

    def test_ntlm_auth(self):
        def isLastExpectedMessage(msg):
            DESC = "PAM_AUTH, ntlm_auth"
            return (
                msg["type"] == "Authentication"
                and msg["Authentication"]["serviceDescription"] == "winbind"
                and msg["Authentication"]["authDescription"] is not None
                and msg["Authentication"]["authDescription"].startswith(DESC))

        pipe = self.dc_watcher()
        COMMAND = "bin/ntlm_auth"
        self.check_run("{0} --username={1} --password={2}".format(
            COMMAND, self.credentials.get_username(),
            self.credentials.get_password()),
                       msg="ntlm_auth failed")

        messages = self.waitForMessages(isLastExpectedMessage)
        messages = self.filter_messages(messages)
        expected_messages = 1
        self.assertEquals(expected_messages, len(messages),
                          "Did not receive the expected number of messages")

        # Check the first message it should be an Authentication
        msg = messages[0]
        self.assertEquals("Authentication", msg["type"])
        self.assertTrue(msg["Authentication"]["authDescription"].startswith(
            "PAM_AUTH, ntlm_auth,"))
        self.assertEquals("winbind",
                          msg["Authentication"]["serviceDescription"])
        self.assertEquals("Plaintext", msg["Authentication"]["passwordType"])
        # Logon type should be NetworkCleartext
        self.assertEquals(8, msg["Authentication"]["logonType"])
        # Event code should be Successful logon
        self.assertEquals(4624, msg["Authentication"]["eventId"])
        self.assertEquals("unix:", msg["Authentication"]["remoteAddress"])
        self.assertEquals("unix:", msg["Authentication"]["localAddress"])
        self.assertEquals(self.domain, msg["Authentication"]["clientDomain"])
        self.assertEquals("NT_STATUS_OK", msg["Authentication"]["status"])
        self.assertEquals(self.credentials.get_username(),
                          msg["Authentication"]["clientAccount"])
        self.assertEquals(self.credentials.get_domain(),
                          msg["Authentication"]["clientDomain"])
        self.assertTrue(msg["Authentication"]["workstation"] is None)

        logon_id = msg["Authentication"]["logonId"]

        #
        # Now check the Domain server authentication message
        #
        self.check_domain_server_authentication(pipe, logon_id, "interactive")

    def test_wbinfo(self):
        def isLastExpectedMessage(msg):
            DESC = "NTLM_AUTH, wbinfo"
            return (
                msg["type"] == "Authentication"
                and msg["Authentication"]["serviceDescription"] == "winbind"
                and msg["Authentication"]["authDescription"] is not None
                and msg["Authentication"]["authDescription"].startswith(DESC))

        pipe = self.dc_watcher()
        COMMAND = "bin/wbinfo"
        try:
            self.check_run("{0} -a {1}%{2}".format(
                COMMAND, self.credentials.get_username(),
                self.credentials.get_password()),
                           msg="ntlm_auth failed")
        except BlackboxProcessError:
            pass

        messages = self.waitForMessages(isLastExpectedMessage)
        messages = self.filter_messages(messages)
        expected_messages = 3
        self.assertEquals(expected_messages, len(messages),
                          "Did not receive the expected number of messages")

        # The 1st message should be an Authentication against the local
        # password database
        msg = messages[0]
        self.assertEquals("Authentication", msg["type"])
        self.assertTrue(msg["Authentication"]["authDescription"].startswith(
            "PASSDB, wbinfo,"))
        self.assertEquals("winbind",
                          msg["Authentication"]["serviceDescription"])
        # Logon type should be Interactive
        self.assertEquals(2, msg["Authentication"]["logonType"])
        # Event code should be Unsuccessful logon
        self.assertEquals(4625, msg["Authentication"]["eventId"])
        self.assertEquals("unix:", msg["Authentication"]["remoteAddress"])
        self.assertEquals("unix:", msg["Authentication"]["localAddress"])
        self.assertEquals('', msg["Authentication"]["clientDomain"])
        # This is what the existing winbind implementation returns.
        self.assertEquals("NT_STATUS_NO_SUCH_USER",
                          msg["Authentication"]["status"])
        self.assertEquals("NTLMv2", msg["Authentication"]["passwordType"])
        self.assertEquals(self.credentials.get_username(),
                          msg["Authentication"]["clientAccount"])
        self.assertEquals("", msg["Authentication"]["clientDomain"])

        logon_id = msg["Authentication"]["logonId"]

        # The 2nd message should be a PAM_AUTH with the same logon id as the
        # 1st message
        msg = messages[1]
        self.assertEquals("Authentication", msg["type"])
        self.assertTrue(
            msg["Authentication"]["authDescription"].startswith("PAM_AUTH"))
        self.assertEquals("winbind",
                          msg["Authentication"]["serviceDescription"])
        self.assertEquals(logon_id, msg["Authentication"]["logonId"])
        # Logon type should be NetworkCleartext
        self.assertEquals(8, msg["Authentication"]["logonType"])
        # Event code should be Unsuccessful logon
        self.assertEquals(4625, msg["Authentication"]["eventId"])
        self.assertEquals("unix:", msg["Authentication"]["remoteAddress"])
        self.assertEquals("unix:", msg["Authentication"]["localAddress"])
        self.assertEquals('', msg["Authentication"]["clientDomain"])
        # This is what the existing winbind implementation returns.
        self.assertEquals("NT_STATUS_INVALID_HANDLE",
                          msg["Authentication"]["status"])
        self.assertEquals(self.credentials.get_username(),
                          msg["Authentication"]["clientAccount"])
        self.assertEquals("", msg["Authentication"]["clientDomain"])

        # The 3rd message should be an NTLM_AUTH
        msg = messages[2]
        self.assertEquals("Authentication", msg["type"])
        self.assertTrue(msg["Authentication"]["authDescription"].startswith(
            "NTLM_AUTH, wbinfo,"))
        self.assertEquals("winbind",
                          msg["Authentication"]["serviceDescription"])
        # Logon type should be Network
        self.assertEquals(3, msg["Authentication"]["logonType"])
        self.assertEquals("NT_STATUS_OK", msg["Authentication"]["status"])
        # Event code should be successful logon
        self.assertEquals(4624, msg["Authentication"]["eventId"])
        self.assertEquals("NTLMv2", msg["Authentication"]["passwordType"])
        self.assertEquals("unix:", msg["Authentication"]["remoteAddress"])
        self.assertEquals("unix:", msg["Authentication"]["localAddress"])
        self.assertEquals(self.credentials.get_username(),
                          msg["Authentication"]["clientAccount"])
        self.assertEquals(self.credentials.get_domain(),
                          msg["Authentication"]["clientDomain"])

        logon_id = msg["Authentication"]["logonId"]

        #
        # Now check the Domain server authentication message
        #
        self.check_domain_server_authentication(pipe, logon_id, "network")

    def test_wbinfo_ntlmv1(self):
        def isLastExpectedMessage(msg):
            DESC = "NTLM_AUTH, wbinfo"
            return (
                msg["type"] == "Authentication"
                and msg["Authentication"]["serviceDescription"] == "winbind"
                and msg["Authentication"]["authDescription"] is not None
                and msg["Authentication"]["authDescription"].startswith(DESC))

        pipe = self.dc_watcher()
        COMMAND = "bin/wbinfo"
        try:
            self.check_run("{0} --ntlmv1 -a {1}%{2}".format(
                COMMAND, self.credentials.get_username(),
                self.credentials.get_password()),
                           msg="ntlm_auth failed")
        except BlackboxProcessError:
            pass

        messages = self.waitForMessages(isLastExpectedMessage)
        messages = self.filter_messages(messages)
        expected_messages = 3
        self.assertEquals(expected_messages, len(messages),
                          "Did not receive the expected number of messages")

        # The 1st message should be an Authentication against the local
        # password database
        msg = messages[0]
        self.assertEquals("Authentication", msg["type"])
        self.assertTrue(msg["Authentication"]["authDescription"].startswith(
            "PASSDB, wbinfo,"))
        self.assertEquals("winbind",
                          msg["Authentication"]["serviceDescription"])
        # Logon type should be Interactive
        self.assertEquals(2, msg["Authentication"]["logonType"])
        # Event code should be Unsuccessful logon
        self.assertEquals(4625, msg["Authentication"]["eventId"])
        self.assertEquals("unix:", msg["Authentication"]["remoteAddress"])
        self.assertEquals("unix:", msg["Authentication"]["localAddress"])
        self.assertEquals('', msg["Authentication"]["clientDomain"])
        # This is what the existing winbind implementation returns.
        self.assertEquals("NT_STATUS_NO_SUCH_USER",
                          msg["Authentication"]["status"])
        self.assertEquals("NTLMv2", msg["Authentication"]["passwordType"])
        self.assertEquals(self.credentials.get_username(),
                          msg["Authentication"]["clientAccount"])
        self.assertEquals("", msg["Authentication"]["clientDomain"])

        logon_id = msg["Authentication"]["logonId"]

        # The 2nd message should be a PAM_AUTH with the same logon id as the
        # 1st message
        msg = messages[1]
        self.assertEquals("Authentication", msg["type"])
        self.assertTrue(
            msg["Authentication"]["authDescription"].startswith("PAM_AUTH"))
        self.assertEquals("winbind",
                          msg["Authentication"]["serviceDescription"])
        self.assertEquals(logon_id, msg["Authentication"]["logonId"])
        self.assertEquals("Plaintext", msg["Authentication"]["passwordType"])
        # Logon type should be NetworkCleartext
        self.assertEquals(8, msg["Authentication"]["logonType"])
        # Event code should be Unsuccessful logon
        self.assertEquals(4625, msg["Authentication"]["eventId"])
        self.assertEquals("unix:", msg["Authentication"]["remoteAddress"])
        self.assertEquals("unix:", msg["Authentication"]["localAddress"])
        self.assertEquals('', msg["Authentication"]["clientDomain"])
        # This is what the existing winbind implementation returns.
        self.assertEquals("NT_STATUS_INVALID_HANDLE",
                          msg["Authentication"]["status"])
        self.assertEquals(self.credentials.get_username(),
                          msg["Authentication"]["clientAccount"])
        self.assertEquals("", msg["Authentication"]["clientDomain"])

        # The 3rd message should be an NTLM_AUTH
        msg = messages[2]
        self.assertEquals("Authentication", msg["type"])
        self.assertTrue(msg["Authentication"]["authDescription"].startswith(
            "NTLM_AUTH, wbinfo,"))
        self.assertEquals("winbind",
                          msg["Authentication"]["serviceDescription"])
        self.assertEquals("NTLMv1", msg["Authentication"]["passwordType"])
        # Logon type should be Network
        self.assertEquals(3, msg["Authentication"]["logonType"])
        self.assertEquals("NT_STATUS_OK", msg["Authentication"]["status"])
        # Event code should be successful logon
        self.assertEquals(4624, msg["Authentication"]["eventId"])
        self.assertEquals("unix:", msg["Authentication"]["remoteAddress"])
        self.assertEquals("unix:", msg["Authentication"]["localAddress"])
        self.assertEquals(self.credentials.get_username(),
                          msg["Authentication"]["clientAccount"])
        self.assertEquals(self.credentials.get_domain(),
                          msg["Authentication"]["clientDomain"])

        logon_id = msg["Authentication"]["logonId"]
        #
        # Now check the Domain server authentication message
        #
        self.check_domain_server_authentication(pipe, logon_id, "network")
Example #47
0
class LDAPBackend(ProvisionBackend):
    def __init__(self,
                 backend_type,
                 paths=None,
                 lp=None,
                 names=None,
                 logger=None,
                 domainsid=None,
                 schema=None,
                 hostname=None,
                 ldapadminpass=None,
                 slapd_path=None,
                 ldap_backend_extra_port=None,
                 ldap_backend_forced_uri=None,
                 ldap_dryrun_mode=False):

        super(LDAPBackend, self).__init__(backend_type=backend_type,
                                          paths=paths,
                                          lp=lp,
                                          names=names,
                                          logger=logger)

        self.domainsid = domainsid
        self.schema = schema
        self.hostname = hostname

        self.ldapdir = os.path.join(paths.private_dir, "ldap")
        self.ldapadminpass = ldapadminpass

        self.slapd_path = slapd_path
        self.slapd_command = None
        self.slapd_command_escaped = None
        self.slapd_pid = os.path.join(self.ldapdir, "slapd.pid")

        self.ldap_backend_extra_port = ldap_backend_extra_port
        self.ldap_dryrun_mode = ldap_dryrun_mode

        if ldap_backend_forced_uri is not None:
            self.ldap_uri = ldap_backend_forced_uri
        else:
            self.ldap_uri = "ldapi://%s" % urllib_quote(
                os.path.join(self.ldapdir, "ldapi"), safe="")

        if not os.path.exists(self.ldapdir):
            os.mkdir(self.ldapdir)

    def init(self):
        from samba.provision import ProvisioningError
        # we will shortly start slapd with ldapi for final provisioning. first
        # check with ldapsearch -> rootDSE via self.ldap_uri if another
        # instance of slapd is already running
        try:
            ldapi_db = Ldb(self.ldap_uri)
            ldapi_db.search(base="",
                            scope=SCOPE_BASE,
                            expression="(objectClass=OpenLDAProotDSE)")
            try:
                f = open(self.slapd_pid, "r")
            except IOError as err:
                if err != errno.ENOENT:
                    raise
            else:
                try:
                    p = f.read()
                finally:
                    f.close()
                self.logger.info(
                    "Check for slapd process with PID: %s and terminate it manually."
                    % p)
            raise SlapdAlreadyRunning(self.ldap_uri)
        except LdbError:
            # XXX: We should never be catching all Ldb errors
            pass

        # Try to print helpful messages when the user has not specified the
        # path to slapd
        if self.slapd_path is None:
            raise ProvisioningError(
                "Warning: LDAP-Backend must be setup with path to slapd, e.g. --slapd-path=\"/usr/local/libexec/slapd\"!"
            )
        if not os.path.exists(self.slapd_path):
            self.logger.warning("Path (%s) to slapd does not exist!",
                                self.slapd_path)

        if not os.path.isdir(self.ldapdir):
            os.makedirs(self.ldapdir, 0o700)

        # Put the LDIF of the schema into a database so we can search on
        # it to generate schema-dependent configurations in Fedora DS and
        # OpenLDAP
        schemadb_path = os.path.join(self.ldapdir, "schema-tmp.ldb")
        try:
            os.unlink(schemadb_path)
        except OSError:
            pass

        self.schema.write_to_tmp_ldb(schemadb_path)

        self.credentials = Credentials()
        self.credentials.guess(self.lp)
        # Kerberos to an ldapi:// backend makes no sense (we also force EXTERNAL)
        self.credentials.set_kerberos_state(DONT_USE_KERBEROS)
        self.credentials.set_username("samba-admin")
        self.credentials.set_password(self.ldapadminpass)
        self.credentials.set_forced_sasl_mech("EXTERNAL")

        self.provision()

    def provision(self):
        pass

    def start(self):
        from samba.provision import ProvisioningError
        self.slapd_command_escaped = "\'" + "\' \'".join(
            self.slapd_command) + "\'"
        ldap_backend_script = os.path.join(self.ldapdir,
                                           "ldap_backend_startup.sh")
        f = open(ldap_backend_script, 'w')
        try:
            f.write("#!/bin/sh\n" + self.slapd_command_escaped + " $@\n")
        finally:
            f.close()

        os.chmod(ldap_backend_script, 0o755)

        # Now start the slapd, so we can provision onto it.  We keep the
        # subprocess context around, to kill this off at the successful
        # end of the script
        self.slapd = subprocess.Popen(self.slapd_provision_command,
                                      close_fds=True,
                                      shell=False)

        count = 0
        while self.slapd.poll() is None:
            # Wait until the socket appears
            try:
                time.sleep(1)
                ldapi_db = Ldb(self.ldap_uri,
                               lp=self.lp,
                               credentials=self.credentials)
                ldapi_db.search(base="",
                                scope=SCOPE_BASE,
                                expression="(objectClass=OpenLDAProotDSE)")
                # If we have got here, then we must have a valid connection to
                # the LDAP server!
                return
            except LdbError:
                count = count + 1

                if count > 15:
                    self.logger.error(
                        "Could not connect to slapd started with: %s" % "\'" +
                        "\' \'".join(self.slapd_provision_command) + "\'")
                    raise ProvisioningError(
                        "slapd never accepted a connection within 15 seconds of starting"
                    )

        self.logger.error("Could not start slapd with: %s" % "\'" +
                          "\' \'".join(self.slapd_provision_command) + "\'")
        raise ProvisioningError(
            "slapd died before we could make a connection to it")

    def shutdown(self):
        # if an LDAP backend is in use, terminate slapd after final provision
        # and check its proper termination
        if self.slapd.poll() is None:
            # Kill the slapd
            if getattr(self.slapd, "terminate", None) is not None:
                self.slapd.terminate()
            else:
                # Older python versions don't have .terminate()
                import signal
                os.kill(self.slapd.pid, signal.SIGTERM)

            # and now wait for it to die
            self.slapd.communicate()

    def post_setup(self):
        return LDAPBackendResult(self.slapd_command_escaped, self.ldapdir)
Example #48
0
    def test_msDSRevealedUsers_using_other_RODC(self):
        """
        Ensure that the machine account is tied to the destination DSA.
        """
        # Create a new identical RODC with just the first letter missing
        other_rodc_name = self.rodc_name[1:]
        other_rodc_ctx = DCJoinContext(server=self.ldb_dc1.host_dns_name(),
                                       creds=self.get_credentials(),
                                       lp=self.get_loadparm(), site=self.site,
                                       netbios_name=other_rodc_name,
                                       targetdir=None, domain=None,
                                       machinepass=self.rodc_pass)
        self._create_rodc(other_rodc_ctx)

        other_rodc_creds = Credentials()
        other_rodc_creds.guess(other_rodc_ctx.lp)
        other_rodc_creds.set_username(other_rodc_name + '$')
        other_rodc_creds.set_password(self.rodc_pass)

        (other_rodc_drs, other_rodc_drs_handle) = self._ds_bind(self.dnsname_dc1, other_rodc_creds)

        rand = random.randint(1, 10000000)
        expected_user_attributes = [drsuapi.DRSUAPI_ATTID_lmPwdHistory,
                                    drsuapi.DRSUAPI_ATTID_supplementalCredentials,
                                    drsuapi.DRSUAPI_ATTID_ntPwdHistory,
                                    drsuapi.DRSUAPI_ATTID_unicodePwd,
                                    drsuapi.DRSUAPI_ATTID_dBCSPwd]

        user_name = "test_rodcF_%s" % rand
        user_dn = "CN=%s,%s" % (user_name, self.ou)
        self.ldb_dc1.add({
            "dn": user_dn,
            "objectclass": "user",
            "sAMAccountName": user_name
        })

        # Store some secret on this user
        self.ldb_dc1.setpassword("(sAMAccountName=%s)" % user_name, 'penguin12#', False, user_name)
        self.ldb_dc1.add_remove_group_members("Allowed RODC Password Replication Group",
                                              [user_name],
                                              add_members_operation=True)

        req10 = self._getnc_req10(dest_dsa=str(other_rodc_ctx.ntds_guid),
                                  invocation_id=self.ldb_dc1.get_invocation_id(),
                                  nc_dn_str=user_dn,
                                  exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET,
                                  partial_attribute_set=drs_get_rodc_partial_attribute_set(self.ldb_dc1, self.tmp_samdb),
                                  max_objects=133,
                                  replica_flags=0)

        try:
            (level, ctr) = self.rodc_drs.DsGetNCChanges(self.rodc_drs_handle, 10, req10)
            self.fail("Successfully replicated secrets to an RODC that shouldn't have been replicated.")
        except WERRORError as e3:
            (enum, estr) = e3.args
            self.assertEqual(enum, 8630)  # ERROR_DS_DRA_SECRETS_DENIED

        req10 = self._getnc_req10(dest_dsa=str(self.rodc_ctx.ntds_guid),
                                  invocation_id=self.ldb_dc1.get_invocation_id(),
                                  nc_dn_str=user_dn,
                                  exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET,
                                  partial_attribute_set=drs_get_rodc_partial_attribute_set(self.ldb_dc1, self.tmp_samdb),
                                  max_objects=133,
                                  replica_flags=0)

        try:
            (level, ctr) = other_rodc_drs.DsGetNCChanges(other_rodc_drs_handle, 10, req10)
            self.fail("Successfully replicated secrets to an RODC that shouldn't have been replicated.")
        except WERRORError as e4:
            (enum, estr) = e4.args
            self.assertEqual(enum, 8630)  # ERROR_DS_DRA_SECRETS_DENIED
Example #49
0
    def _test_samlogon(self, binding, creds, checkFunction):

        def isLastExpectedMessage(msg):
            return (
                msg["type"] == "Authentication" and
                msg["Authentication"]["serviceDescription"]  == "SamLogon" and
                msg["Authentication"]["authDescription"]     == "network" and
                msg["Authentication"]["passwordType"]        == "NTLMv2" and
                (msg["Authentication"]["eventId"] ==
                    EVT_ID_SUCCESSFUL_LOGON) and
                (msg["Authentication"]["logonType"] == EVT_LOGON_NETWORK))

        if binding:
            binding = "[schannel,%s]" % binding
        else:
            binding = "[schannel]"

        utf16pw = text_type('"' + self.machinepass + '"').encode('utf-16-le')
        self.ldb.add({
            "dn": self.samlogon_dn,
            "objectclass": "computer",
            "sAMAccountName": "%s$" % self.netbios_name,
            "userAccountControl":
                str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
            "unicodePwd": utf16pw})

        machine_creds = Credentials()
        machine_creds.guess(self.get_loadparm())
        machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
        machine_creds.set_password(self.machinepass)
        machine_creds.set_username(self.netbios_name + "$")

        netlogon_conn = netlogon.netlogon("ncalrpc:%s" % binding,
                                          self.get_loadparm(),
                                          machine_creds)
        challenge = b"abcdefgh"

        target_info = ntlmssp.AV_PAIR_LIST()
        target_info.count = 3

        domainname = ntlmssp.AV_PAIR()
        domainname.AvId = ntlmssp.MsvAvNbDomainName
        domainname.Value = self.domain

        computername = ntlmssp.AV_PAIR()
        computername.AvId = ntlmssp.MsvAvNbComputerName
        computername.Value = self.netbios_name

        eol = ntlmssp.AV_PAIR()
        eol.AvId = ntlmssp.MsvAvEOL
        target_info.pair = [domainname, computername, eol]

        target_info_blob = ndr_pack(target_info)

        response = creds.get_ntlm_response(flags=CLI_CRED_NTLMv2_AUTH,
                                           challenge=challenge,
                                           target_info=target_info_blob)

        netr_flags = 0

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        logon = samba.dcerpc.netlogon.netr_NetworkInfo()

        logon.challenge = [x if isinstance(x,int) else ord(x) for x in challenge]
        logon.nt = netlogon.netr_ChallengeResponse()
        logon.nt.length = len(response["nt_response"])
        logon.nt.data = [x if isinstance(x,int) else ord(x) for x in response["nt_response"]]
        logon.identity_info = samba.dcerpc.netlogon.netr_IdentityInfo()
        (username, domain) = creds.get_ntlm_username_domain()

        logon.identity_info.domain_name.string = domain
        logon.identity_info.account_name.string = username
        logon.identity_info.workstation.string = creds.get_workstation()

        validation_level = samba.dcerpc.netlogon.NetlogonValidationSamInfo4

        result = netlogon_conn.netr_LogonSamLogonEx(
            os.environ["SERVER"],
            machine_creds.get_workstation(),
            logon_level, logon,
            validation_level, netr_flags)

        (validation, authoritative, netr_flags_out) = result

        messages = self.waitForMessages(isLastExpectedMessage, netlogon_conn)
        checkFunction(messages)
class BasePasswordTestCase(PasswordTestCase):
    def _open_samr_user(self, res):
        self.assertTrue("objectSid" in res[0])

        (domain_sid, rid) = ndr_unpack(security.dom_sid,
                                       res[0]["objectSid"][0]).split()
        self.assertEquals(self.domain_sid, domain_sid)

        return self.samr.OpenUser(self.samr_domain,
                                  security.SEC_FLAG_MAXIMUM_ALLOWED, rid)

    def _check_attribute(self, res, name, value):
        if value is None:
            self.assertTrue(name not in res[0],
                            msg="attr[%s]=%r on dn[%s]" %
                            (name, res[0], res[0].dn))
            return

        if isinstance(value, tuple):
            (mode, value) = value
        else:
            mode = "equal"

        if mode == "ignore":
            return

        if mode == "absent":
            self.assertFalse(name in res[0],
                             msg="attr[%s] not missing on dn[%s]" %
                             (name, res[0].dn))
            return

        self.assertTrue(name in res[0],
                        msg="attr[%s] missing on dn[%s]" % (name, res[0].dn))
        self.assertTrue(len(res[0][name]) == 1,
                        msg="attr[%s]=%r on dn[%s]" %
                        (name, res[0][name], res[0].dn))

        print("%s = '%s'" % (name, res[0][name][0]))

        if mode == "present":
            return

        if mode == "equal":
            v = int(res[0][name][0])
            value = int(value)
            msg = ("attr[%s]=[%s] != [%s] on dn[%s]\n"
                   "(diff %d; actual value is %s than expected)" %
                   (name, v, value, res[0].dn, v - value,
                    ('less' if v < value else 'greater')))

            self.assertTrue(v == value, msg)
            return

        if mode == "greater":
            v = int(res[0][name][0])
            self.assertTrue(v > int(value),
                            msg="attr[%s]=[%s] <= [%s] on dn[%s] (diff %d)" %
                            (name, v, int(value), res[0].dn, v - int(value)))
            return
        if mode == "less":
            v = int(res[0][name][0])
            self.assertTrue(v < int(value),
                            msg="attr[%s]=[%s] >= [%s] on dn[%s] (diff %d)" %
                            (name, v, int(value), res[0].dn, v - int(value)))
            return
        self.assertEqual(mode, not mode, "Invalid Mode[%s]" % mode)

    def _check_account_initial(self, userdn):
        self._check_account(userdn,
                            badPwdCount=0,
                            badPasswordTime=0,
                            logonCount=0,
                            lastLogon=0,
                            lastLogonTimestamp=("absent", None),
                            userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                            msDSUserAccountControlComputed=0)

    def _check_account(self,
                       dn,
                       badPwdCount=None,
                       badPasswordTime=None,
                       logonCount=None,
                       lastLogon=None,
                       lastLogonTimestamp=None,
                       lockoutTime=None,
                       userAccountControl=None,
                       msDSUserAccountControlComputed=None,
                       effective_bad_password_count=None,
                       msg=None,
                       badPwdCountOnly=False):
        print('-=' * 36)
        if msg is not None:
            print("\033[01;32m %s \033[00m\n" % msg)
        attrs = [
            "objectSid", "badPwdCount", "badPasswordTime", "lastLogon",
            "lastLogonTimestamp", "logonCount", "lockoutTime",
            "userAccountControl", "msDS-User-Account-Control-Computed"
        ]

        # in order to prevent some time resolution problems we sleep for
        # 10 micro second
        time.sleep(0.01)

        res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs)
        self.assertTrue(len(res) == 1)
        self._check_attribute(res, "badPwdCount", badPwdCount)
        self._check_attribute(res, "lockoutTime", lockoutTime)
        self._check_attribute(res, "badPasswordTime", badPasswordTime)
        if not badPwdCountOnly:
            self._check_attribute(res, "logonCount", logonCount)
            self._check_attribute(res, "lastLogon", lastLogon)
            self._check_attribute(res, "lastLogonTimestamp",
                                  lastLogonTimestamp)
            self._check_attribute(res, "userAccountControl",
                                  userAccountControl)
            self._check_attribute(res, "msDS-User-Account-Control-Computed",
                                  msDSUserAccountControlComputed)

            lastLogon = int(res[0]["lastLogon"][0])
            logonCount = int(res[0]["logonCount"][0])

        samr_user = self._open_samr_user(res)
        uinfo3 = self.samr.QueryUserInfo(samr_user, 3)
        uinfo5 = self.samr.QueryUserInfo(samr_user, 5)
        uinfo16 = self.samr.QueryUserInfo(samr_user, 16)
        uinfo21 = self.samr.QueryUserInfo(samr_user, 21)
        self.samr.Close(samr_user)

        expected_acb_info = 0
        if not badPwdCountOnly:
            if userAccountControl & dsdb.UF_NORMAL_ACCOUNT:
                expected_acb_info |= samr.ACB_NORMAL
            if userAccountControl & dsdb.UF_ACCOUNTDISABLE:
                expected_acb_info |= samr.ACB_DISABLED
            if userAccountControl & dsdb.UF_PASSWD_NOTREQD:
                expected_acb_info |= samr.ACB_PWNOTREQ
            if msDSUserAccountControlComputed & dsdb.UF_LOCKOUT:
                expected_acb_info |= samr.ACB_AUTOLOCK
            if msDSUserAccountControlComputed & dsdb.UF_PASSWORD_EXPIRED:
                expected_acb_info |= samr.ACB_PW_EXPIRED

            self.assertEquals(uinfo3.acct_flags, expected_acb_info)
            self.assertEquals(uinfo3.last_logon, lastLogon)
            self.assertEquals(uinfo3.logon_count, logonCount)

        expected_bad_password_count = 0
        if badPwdCount is not None:
            expected_bad_password_count = badPwdCount
        if effective_bad_password_count is None:
            effective_bad_password_count = expected_bad_password_count

        self.assertEquals(uinfo3.bad_password_count,
                          expected_bad_password_count)

        if not badPwdCountOnly:
            self.assertEquals(uinfo5.acct_flags, expected_acb_info)
            self.assertEquals(uinfo5.bad_password_count,
                              effective_bad_password_count)
            self.assertEquals(uinfo5.last_logon, lastLogon)
            self.assertEquals(uinfo5.logon_count, logonCount)

            self.assertEquals(uinfo16.acct_flags, expected_acb_info)

            self.assertEquals(uinfo21.acct_flags, expected_acb_info)
            self.assertEquals(uinfo21.bad_password_count,
                              effective_bad_password_count)
            self.assertEquals(uinfo21.last_logon, lastLogon)
            self.assertEquals(uinfo21.logon_count, logonCount)

        # check LDAP again and make sure the samr.QueryUserInfo
        # doesn't have any impact.
        res2 = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs)
        self.assertEquals(res[0], res2[0])

        # in order to prevent some time resolution problems we sleep for
        # 10 micro second
        time.sleep(0.01)
        return res

    def update_lockout_settings(self, threshold, duration, observation_window):
        """Updates the global user lockout settings"""
        m = Message()
        m.dn = Dn(self.ldb, self.base_dn)
        account_lockout_duration_ticks = -int(duration * (1e7))
        m["lockoutDuration"] = MessageElement(
            str(account_lockout_duration_ticks), FLAG_MOD_REPLACE,
            "lockoutDuration")
        m["lockoutThreshold"] = MessageElement(str(threshold),
                                               FLAG_MOD_REPLACE,
                                               "lockoutThreshold")
        lockout_observation_window_ticks = -int(observation_window * (1e7))
        m["lockOutObservationWindow"] = MessageElement(
            str(lockout_observation_window_ticks), FLAG_MOD_REPLACE,
            "lockOutObservationWindow")
        self.ldb.modify(m)

    def _readd_user(self, creds, lockOutObservationWindow=0):
        username = creds.get_username()
        userpass = creds.get_password()
        userdn = "cn=%s,cn=users,%s" % (username, self.base_dn)

        delete_force(self.ldb, userdn)
        self.ldb.add({
            "dn": userdn,
            "objectclass": "user",
            "sAMAccountName": username
        })

        self.addCleanup(delete_force, self.ldb, userdn)

        # Sets the initial user password with a "special" password change
        # I think that this internally is a password set operation and it can
        # only be performed by someone which has password set privileges on the
        # account (at least in s4 we do handle it like that).
        self.ldb.modify_ldif("""
dn: """ + userdn + """
changetype: modify
delete: userPassword
add: userPassword
userPassword: """ + userpass + """
""")
        # Enables the user account
        self.ldb.enable_account("(sAMAccountName=%s)" % username)

        use_kerberos = creds.get_kerberos_state()
        fail_creds = self.insta_creds(self.template_creds,
                                      username=username,
                                      userpass=userpass + "X",
                                      kerberos_state=use_kerberos)
        self._check_account_initial(userdn)

        # Fail once to get a badPasswordTime
        try:
            ldb = SamDB(url=self.host_url, credentials=fail_creds, lp=self.lp)
            self.fail()
        except LdbError as e:
            (num, msg) = e.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        # Succeed to reset everything to 0
        ldb = SamDB(url=self.host_url, credentials=creds, lp=self.lp)

        return ldb

    def assertLoginFailure(self,
                           url,
                           creds,
                           lp,
                           errno=ERR_INVALID_CREDENTIALS):
        try:
            ldb = SamDB(url=url, credentials=creds, lp=lp)
            self.fail("Login unexpectedly succeeded")
        except LdbError as e1:
            (num, msg) = e1.args
            if errno is not None:
                self.assertEquals(num, errno,
                                  ("Login failed in the wrong way"
                                   "(got err %d, expected %d)" % (num, errno)))

    def setUp(self):
        super(BasePasswordTestCase, self).setUp()

        self.global_creds.set_gensec_features(
            self.global_creds.get_gensec_features() | gensec.FEATURE_SEAL)

        self.template_creds = Credentials()
        self.template_creds.set_username("testuser")
        self.template_creds.set_password("thatsAcomplPASS1")
        self.template_creds.set_domain(self.global_creds.get_domain())
        self.template_creds.set_realm(self.global_creds.get_realm())
        self.template_creds.set_workstation(
            self.global_creds.get_workstation())
        self.template_creds.set_gensec_features(
            self.global_creds.get_gensec_features())
        self.template_creds.set_kerberos_state(
            self.global_creds.get_kerberos_state())

        # Gets back the basedn
        base_dn = self.ldb.domain_dn()

        # Gets back the configuration basedn
        configuration_dn = self.ldb.get_config_basedn().get_linearized()

        res = self.ldb.search(base_dn,
                              scope=SCOPE_BASE,
                              attrs=[
                                  "lockoutDuration",
                                  "lockOutObservationWindow",
                                  "lockoutThreshold"
                              ])

        if "lockoutDuration" in res[0]:
            lockoutDuration = res[0]["lockoutDuration"][0]
        else:
            lockoutDuration = 0

        if "lockoutObservationWindow" in res[0]:
            lockoutObservationWindow = res[0]["lockoutObservationWindow"][0]
        else:
            lockoutObservationWindow = 0

        if "lockoutThreshold" in res[0]:
            lockoutThreshold = res[0]["lockoutThreshold"][0]
        else:
            lockoutTreshold = 0

        self.addCleanup(
            self.ldb.modify_ldif, """
dn: """ + base_dn + """
changetype: modify
replace: lockoutDuration
lockoutDuration: """ + str(lockoutDuration) + """
replace: lockoutObservationWindow
lockoutObservationWindow: """ + str(lockoutObservationWindow) + """
replace: lockoutThreshold
lockoutThreshold: """ + str(lockoutThreshold) + """
""")

        self.base_dn = self.ldb.domain_dn()

        #
        # Some test cases sleep() for self.account_lockout_duration
        # so allow it to be controlled via the subclass
        #
        if not hasattr(self, 'account_lockout_duration'):
            self.account_lockout_duration = 3
        if not hasattr(self, 'lockout_observation_window'):
            self.lockout_observation_window = 3
        self.update_lockout_settings(
            threshold=3,
            duration=self.account_lockout_duration,
            observation_window=self.lockout_observation_window)

        # update DC to allow password changes for the duration of this test
        self.allow_password_changes()

        self.domain_sid = security.dom_sid(self.ldb.get_domain_sid())
        self.samr = samr.samr("ncacn_ip_tcp:%s[seal]" % self.host, self.lp,
                              self.global_creds)
        self.samr_handle = self.samr.Connect2(
            None, security.SEC_FLAG_MAXIMUM_ALLOWED)
        self.samr_domain = self.samr.OpenDomain(
            self.samr_handle, security.SEC_FLAG_MAXIMUM_ALLOWED,
            self.domain_sid)

        self.addCleanup(self.delete_ldb_connections)

        # (Re)adds the test user accounts
        self.lockout1krb5_creds = self.insta_creds(
            self.template_creds,
            username="******",
            userpass="******",
            kerberos_state=MUST_USE_KERBEROS)
        self.lockout1krb5_ldb = self._readd_user(self.lockout1krb5_creds)
        self.lockout1ntlm_creds = self.insta_creds(
            self.template_creds,
            username="******",
            userpass="******",
            kerberos_state=DONT_USE_KERBEROS)
        self.lockout1ntlm_ldb = self._readd_user(self.lockout1ntlm_creds)

    def delete_ldb_connections(self):
        del self.lockout1krb5_ldb
        del self.lockout1ntlm_ldb
        del self.ldb

    def tearDown(self):
        super(BasePasswordTestCase, self).tearDown()

    def _test_login_lockout(self, creds):
        username = creds.get_username()
        userpass = creds.get_password()
        userdn = "cn=%s,cn=users,%s" % (username, self.base_dn)

        use_kerberos = creds.get_kerberos_state()
        # This unlocks by waiting for account_lockout_duration
        if use_kerberos == MUST_USE_KERBEROS:
            logoncount_relation = 'greater'
            lastlogon_relation = 'greater'
            print("Performs a lockout attempt against LDAP using Kerberos")
        else:
            logoncount_relation = 'equal'
            lastlogon_relation = 'equal'
            print("Performs a lockout attempt against LDAP using NTLM")

        # Change password on a connection as another user
        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=("greater", 0),
                                  logonCount=(logoncount_relation, 0),
                                  lastLogon=("greater", 0),
                                  lastLogonTimestamp=("greater", 0),
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])
        logonCount = int(res[0]["logonCount"][0])
        lastLogon = int(res[0]["lastLogon"][0])
        firstLogon = lastLogon
        lastLogonTimestamp = int(res[0]["lastLogonTimestamp"][0])
        print(firstLogon)
        print(lastLogonTimestamp)

        self.assertGreater(lastLogon, badPasswordTime)
        self.assertGreaterEqual(lastLogon, lastLogonTimestamp)

        # Open a second LDB connection with the user credentials. Use the
        # command line credentials for informations like the domain, the realm
        # and the workstation.
        creds_lockout = self.insta_creds(creds)

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")

        self.assertLoginFailure(self.host_url, creds_lockout, self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=1,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0,
                                  msg='lastlogontimestamp with wrong password')
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        # Correct old password
        creds_lockout.set_password(userpass)

        ldb_lockout = SamDB(url=self.host_url,
                            credentials=creds_lockout,
                            lp=self.lp)

        # lastLogonTimestamp should not change
        # lastLogon increases if badPwdCount is non-zero (!)
        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lastLogon=('greater', lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0,
                                  msg='LLTimestamp is updated to lastlogon')

        logonCount = int(res[0]["logonCount"][0])
        lastLogon = int(res[0]["lastLogon"][0])
        self.assertGreater(lastLogon, badPasswordTime)
        self.assertGreaterEqual(lastLogon, lastLogonTimestamp)

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")

        self.assertLoginFailure(self.host_url, creds_lockout, self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=1,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")

        try:
            ldb_lockout = SamDB(url=self.host_url,
                                credentials=creds_lockout,
                                lp=self.lp)
            self.fail()

        except LdbError as e2:
            (num, msg) = e2.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=2,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        print("two failed password change")

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")

        try:
            ldb_lockout = SamDB(url=self.host_url,
                                credentials=creds_lockout,
                                lp=self.lp)
            self.fail()

        except LdbError as e3:
            (num, msg) = e3.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(
            userdn,
            badPwdCount=3,
            badPasswordTime=("greater", badPasswordTime),
            logonCount=logonCount,
            lastLogon=lastLogon,
            lastLogonTimestamp=lastLogonTimestamp,
            lockoutTime=("greater", badPasswordTime),
            userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
            msDSUserAccountControlComputed=dsdb.UF_LOCKOUT)
        badPasswordTime = int(res[0]["badPasswordTime"][0])
        lockoutTime = int(res[0]["lockoutTime"][0])

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url,
                                credentials=creds_lockout,
                                lp=self.lp)
            self.fail()
        except LdbError as e4:
            (num, msg) = e4.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(
            userdn,
            badPwdCount=3,
            badPasswordTime=badPasswordTime,
            logonCount=logonCount,
            lastLogon=lastLogon,
            lastLogonTimestamp=lastLogonTimestamp,
            lockoutTime=lockoutTime,
            userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
            msDSUserAccountControlComputed=dsdb.UF_LOCKOUT)

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url,
                                credentials=creds_lockout,
                                lp=self.lp)
            self.fail()
        except LdbError as e5:
            (num, msg) = e5.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(
            userdn,
            badPwdCount=3,
            badPasswordTime=badPasswordTime,
            logonCount=logonCount,
            lastLogon=lastLogon,
            lastLogonTimestamp=lastLogonTimestamp,
            lockoutTime=lockoutTime,
            userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
            msDSUserAccountControlComputed=dsdb.UF_LOCKOUT)

        # The correct password, but we are locked out
        creds_lockout.set_password(userpass)
        try:
            ldb_lockout = SamDB(url=self.host_url,
                                credentials=creds_lockout,
                                lp=self.lp)
            self.fail()
        except LdbError as e6:
            (num, msg) = e6.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(
            userdn,
            badPwdCount=3,
            badPasswordTime=badPasswordTime,
            logonCount=logonCount,
            lastLogon=lastLogon,
            lastLogonTimestamp=lastLogonTimestamp,
            lockoutTime=lockoutTime,
            userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
            msDSUserAccountControlComputed=dsdb.UF_LOCKOUT)

        # wait for the lockout to end
        time.sleep(self.account_lockout_duration + 1)
        print(self.account_lockout_duration + 1)

        res = self._check_account(userdn,
                                  badPwdCount=3,
                                  effective_bad_password_count=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=logonCount,
                                  lockoutTime=lockoutTime,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)

        # The correct password after letting the timeout expire

        creds_lockout.set_password(userpass)

        creds_lockout2 = self.insta_creds(creds_lockout)

        ldb_lockout = SamDB(url=self.host_url,
                            credentials=creds_lockout2,
                            lp=self.lp)
        time.sleep(3)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lastLogon=(lastlogon_relation, lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  lockoutTime=0,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0,
                                  msg="lastLogon is way off")

        logonCount = int(res[0]["logonCount"][0])
        lastLogon = int(res[0]["lastLogon"][0])

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url,
                                credentials=creds_lockout,
                                lp=self.lp)
            self.fail()
        except LdbError as e7:
            (num, msg) = e7.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=1,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lockoutTime=0,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url,
                                credentials=creds_lockout,
                                lp=self.lp)
            self.fail()
        except LdbError as e8:
            (num, msg) = e8.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=2,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lockoutTime=0,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        time.sleep(self.lockout_observation_window + 1)

        res = self._check_account(userdn,
                                  badPwdCount=2,
                                  effective_bad_password_count=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=logonCount,
                                  lockoutTime=0,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)

        # The wrong password
        creds_lockout.set_password("thatsAcomplPASS1x")
        try:
            ldb_lockout = SamDB(url=self.host_url,
                                credentials=creds_lockout,
                                lp=self.lp)
            self.fail()
        except LdbError as e9:
            (num, msg) = e9.args
            self.assertEquals(num, ERR_INVALID_CREDENTIALS)

        res = self._check_account(userdn,
                                  badPwdCount=1,
                                  badPasswordTime=("greater", badPasswordTime),
                                  logonCount=logonCount,
                                  lockoutTime=0,
                                  lastLogon=lastLogon,
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])

        # The correct password without letting the timeout expire
        creds_lockout.set_password(userpass)
        ldb_lockout = SamDB(url=self.host_url,
                            credentials=creds_lockout,
                            lp=self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lockoutTime=0,
                                  lastLogon=("greater", lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)

    def _test_multiple_logon(self, creds):
        # Test the happy case in which a user logs on correctly, then
        # logs on correctly again, so that the bad password and
        # lockout times are both zero the second time. The lastlogon
        # time should increase.

        # Open a second LDB connection with the user credentials. Use the
        # command line credentials for informations like the domain, the realm
        # and the workstation.
        username = creds.get_username()
        userdn = "cn=%s,cn=users,%s" % (username, self.base_dn)

        use_kerberos = creds.get_kerberos_state()
        if use_kerberos == MUST_USE_KERBEROS:
            print("Testing multiple logon with Kerberos")
            logoncount_relation = 'greater'
            lastlogon_relation = 'greater'
        else:
            print("Testing multiple logon with NTLM")
            logoncount_relation = 'equal'
            lastlogon_relation = 'equal'

        SamDB(url=self.host_url,
              credentials=self.insta_creds(creds),
              lp=self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=("greater", 0),
                                  logonCount=(logoncount_relation, 0),
                                  lastLogon=("greater", 0),
                                  lastLogonTimestamp=("greater", 0),
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
        badPasswordTime = int(res[0]["badPasswordTime"][0])
        logonCount = int(res[0]["logonCount"][0])
        lastLogon = int(res[0]["lastLogon"][0])
        lastLogonTimestamp = int(res[0]["lastLogonTimestamp"][0])
        firstLogon = lastLogon
        print("last logon is %d" % lastLogon)
        self.assertGreater(lastLogon, badPasswordTime)
        self.assertGreaterEqual(lastLogon, lastLogonTimestamp)

        time.sleep(1)
        SamDB(url=self.host_url,
              credentials=self.insta_creds(creds),
              lp=self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lastLogon=(lastlogon_relation, lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0,
                                  msg=("second logon, firstlogon was %s" %
                                       firstLogon))

        lastLogon = int(res[0]["lastLogon"][0])

        time.sleep(1)

        SamDB(url=self.host_url,
              credentials=self.insta_creds(creds),
              lp=self.lp)

        res = self._check_account(userdn,
                                  badPwdCount=0,
                                  badPasswordTime=badPasswordTime,
                                  logonCount=(logoncount_relation, logonCount),
                                  lastLogon=(lastlogon_relation, lastLogon),
                                  lastLogonTimestamp=lastLogonTimestamp,
                                  userAccountControl=dsdb.UF_NORMAL_ACCOUNT,
                                  msDSUserAccountControlComputed=0)
Example #51
0
class SamrPasswordTests(RpcInterfaceTestCase):
    def setUp(self):
        super(SamrPasswordTests, self).setUp()
        self.open_samdb()

        self.create_user_account(10000)

        self.remote_server = samba.tests.env_get_var_value('SERVER')
        self.remote_domain = samba.tests.env_get_var_value('DOMAIN')
        self.remote_user = samba.tests.env_get_var_value('USERNAME')
        self.remote_password = samba.tests.env_get_var_value('PASSWORD')
        self.remote_binding_string = "ncacn_np:%s[krb5]" % (self.remote_server)

        self.remote_creds = Credentials()
        self.remote_creds.guess(self.lp)
        self.remote_creds.set_username(self.remote_user)
        self.remote_creds.set_password(self.remote_password)

    def tearDown(self):
        super(SamrPasswordTests, self).tearDown()

        samr.Close(self.user_handle)
        samr.Close(self.domain_handle)
        samr.Close(self.handle)

        samba.tests.delete_force(self.samdb, self.user_dn)

    #
    # Open the samba database
    #
    def open_samdb(self):
        self.lp = samba.tests.env_loadparm()

        self.local_creds = Credentials()
        self.local_creds.guess(self.lp)
        self.session = system_session()
        self.samdb = SamDB(session_info=self.session,
                           credentials=self.local_creds,
                           lp=self.lp)

    #
    # Open a SAMR Domain handle
    #
    def open_domain_handle(self):
        self.handle = self.conn.Connect2(None,
                                         security.SEC_FLAG_MAXIMUM_ALLOWED)

        self.domain_sid = self.conn.LookupDomain(self.handle,
                                                 lsa.String(self.remote_domain))

        self.domain_handle = self.conn.OpenDomain(self.handle,
                                                  security.SEC_FLAG_MAXIMUM_ALLOWED,
                                                  self.domain_sid)

    def open_user_handle(self):
        name = lsa.String(self.user_name)

        rids = self.conn.LookupNames(self.domain_handle, [name])

        self.user_handle = self.conn.OpenUser(self.domain_handle,
                                              security.SEC_FLAG_MAXIMUM_ALLOWED,
                                              rids[0].ids[0])
    #
    # Create a test user account
    #
    def create_user_account(self, user_id):
        self.user_name = ("SAMR_USER_%d" % user_id)
        self.user_pass = generate_random_password(32, 32)
        self.user_dn = "cn=%s,cn=users,%s" % (self.user_name, self.samdb.domain_dn())

        samba.tests.delete_force(self.samdb, self.user_dn)

        self.samdb.newuser(self.user_name,
                           self.user_pass,
                           description="Password for " + self.user_name + " is " + self.user_pass,
                           givenname=self.user_name,
                           surname=self.user_name)


    def init_samr_CryptPassword(self, password, session_key):

        def encode_pw_buffer(password):
            data = bytearray([0] * 516)

            p = samba.string_to_byte_array(password.encode('utf-16-le'))
            plen = len(p)

            b = generate_random_bytes(512 - plen)

            i = 512 - plen
            data[0:i] = b
            data[i:i+plen] = p
            data[512:516] = plen.to_bytes(4, byteorder='little')

            return bytes(data)

        # This is a test, so always allow to encrypt using RC4
        try:
            crypto.set_relax_mode()
            encrypted_blob = samba.arcfour_encrypt(session_key, encode_pw_buffer(password))
        finally:
            crypto.set_strict_mode()

        out_blob = samr.CryptPassword()
        out_blob.data = list(encrypted_blob)

        return out_blob


    def test_setUserInfo2_Password(self, password='******'):
        self.conn = samr.samr(self.remote_binding_string,
                              self.get_loadparm(),
                              self.remote_creds)
        self.open_domain_handle()
        self.open_user_handle()

        password='******'

        level = 24
        info = samr.UserInfo24()

        info.password_expired = 0
        info.password = self.init_samr_CryptPassword(password, self.conn.session_key)

        # If the server is in FIPS mode, it should reject the password change!
        try:
            self.conn.SetUserInfo2(self.user_handle, level, info)
        except samba.NTSTATUSError as e:
            code = ctypes.c_uint32(e.args[0]).value
            print(code)
            if ((code == ntstatus.NT_STATUS_ACCESS_DENIED) and
                (self.lp.weak_crypto == 'disallowed')):
                pass
            else:
                raise


    def test_setUserInfo2_Password_Encrypted(self, password='******'):
        self.remote_creds.set_smb_encryption(SMB_ENCRYPTION_REQUIRED)

        self.conn = samr.samr(self.remote_binding_string,
                              self.get_loadparm(),
                              self.remote_creds)
        self.open_domain_handle()
        self.open_user_handle()

        password='******'

        level = 24
        info = samr.UserInfo24()

        info.password_expired = 0
        info.password = self.init_samr_CryptPassword(password, self.conn.session_key)

        self.conn.SetUserInfo2(self.user_handle, level, info)
Example #52
0
class PyCredentialsTests(TestCase):
    def setUp(self):
        super(PyCredentialsTests, self).setUp()

        self.server = os.environ["SERVER"]
        self.domain = os.environ["DOMAIN"]
        self.host = os.environ["SERVER_IP"]
        self.lp = self.get_loadparm()

        self.credentials = self.get_credentials()

        self.session = system_session()
        self.ldb = SamDB(url="ldap://%s" % self.host,
                         session_info=self.session,
                         credentials=self.credentials,
                         lp=self.lp)

        self.create_machine_account()
        self.create_user_account()

    def tearDown(self):
        super(PyCredentialsTests, self).tearDown()
        delete_force(self.ldb, self.machine_dn)
        delete_force(self.ldb, self.user_dn)

    # Until a successful netlogon connection has been established there will
    # not be a valid authenticator associated with the credentials
    # and new_client_authenticator should throw a ValueError
    def test_no_netlogon_connection(self):
        self.assertRaises(ValueError,
                          self.machine_creds.new_client_authenticator)

    # Once a netlogon connection has been established,
    # new_client_authenticator should return a value
    #
    def test_have_netlogon_connection(self):
        c = self.get_netlogon_connection()
        a = self.machine_creds.new_client_authenticator()
        self.assertIsNotNone(a)

    # Get an authenticator and use it on a sequence of operations requiring
    # an authenticator
    def test_client_authenticator(self):
        c = self.get_netlogon_connection()
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonSamLogonWithFlags(c, authenticator, subsequent)
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)
        (authenticator, subsequent) = self.get_authenticator(c)
        self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)

    # Test Credentials.encrypt_netr_crypt_password
    # By performing a NetrServerPasswordSet2
    # And the logging on using the new password.
    def test_encrypt_netr_password(self):
        # Change the password
        self.do_Netr_ServerPasswordSet2()
        # Now use the new password to perform an operation
        self.do_DsrEnumerateDomainTrusts()

# Change the current machine account pazssword with a
# netr_ServerPasswordSet2 call.

    def do_Netr_ServerPasswordSet2(self):
        c = self.get_netlogon_connection()
        (authenticator, subsequent) = self.get_authenticator(c)
        PWD_LEN = 32
        DATA_LEN = 512
        newpass = samba.generate_random_password(PWD_LEN, PWD_LEN)
        filler = [ord(x) for x in os.urandom(DATA_LEN - PWD_LEN)]
        pwd = netlogon.netr_CryptPassword()
        pwd.length = PWD_LEN
        pwd.data = filler + [ord(x) for x in newpass]
        self.machine_creds.encrypt_netr_crypt_password(pwd)
        c.netr_ServerPasswordSet2(self.server,
                                  self.machine_creds.get_workstation(),
                                  SEC_CHAN_WKSTA, self.machine_name,
                                  authenticator, pwd)

        self.machine_pass = newpass
        self.machine_creds.set_password(newpass)

    # Perform a DsrEnumerateDomainTrusts, this provides confirmation that
    # a netlogon connection has been correctly established
    def do_DsrEnumerateDomainTrusts(self):
        c = self.get_netlogon_connection()
        trusts = c.netr_DsrEnumerateDomainTrusts(
            self.server, netlogon.NETR_TRUST_FLAG_IN_FOREST
            | netlogon.NETR_TRUST_FLAG_OUTBOUND
            | netlogon.NETR_TRUST_FLAG_INBOUND)

    # Establish sealed schannel netlogon connection over TCP/IP
    #
    def get_netlogon_connection(self):
        return netlogon.netlogon(
            "ncacn_ip_tcp:%s[schannel,seal]" % self.server, self.lp,
            self.machine_creds)

    #
    # Create the machine account
    def create_machine_account(self):
        self.machine_pass = samba.generate_random_password(32, 32)
        self.machine_name = MACHINE_NAME
        self.machine_dn = "cn=%s,%s" % (self.machine_name,
                                        self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, self.machine_dn)

        utf16pw = unicode('"' + self.machine_pass.encode('utf-8') + '"',
                          'utf-8').encode('utf-16-le')
        self.ldb.add({
            "dn":
            self.machine_dn,
            "objectclass":
            "computer",
            "sAMAccountName":
            "%s$" % self.machine_name,
            "userAccountControl":
            str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
            "unicodePwd":
            utf16pw
        })

        self.machine_creds = Credentials()
        self.machine_creds.guess(self.get_loadparm())
        self.machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
        self.machine_creds.set_password(self.machine_pass)
        self.machine_creds.set_username(self.machine_name + "$")
        self.machine_creds.set_workstation(self.machine_name)

    #
    # Create a test user account
    def create_user_account(self):
        self.user_pass = samba.generate_random_password(32, 32)
        self.user_name = USER_NAME
        self.user_dn = "cn=%s,%s" % (self.user_name, self.ldb.domain_dn())

        # remove the account if it exists, this will happen if a previous test
        # run failed
        delete_force(self.ldb, self.user_dn)

        utf16pw = unicode('"' + self.user_pass.encode('utf-8') + '"',
                          'utf-8').encode('utf-16-le')
        self.ldb.add({
            "dn": self.user_dn,
            "objectclass": "user",
            "sAMAccountName": "%s" % self.user_name,
            "userAccountControl": str(UF_NORMAL_ACCOUNT),
            "unicodePwd": utf16pw
        })

        self.user_creds = Credentials()
        self.user_creds.guess(self.get_loadparm())
        self.user_creds.set_password(self.user_pass)
        self.user_creds.set_username(self.user_name)
        self.user_creds.set_workstation(self.machine_name)
        pass

    #
    # Get the authenticator from the machine creds.
    def get_authenticator(self, c):
        auth = self.machine_creds.new_client_authenticator()
        current = netr_Authenticator()
        current.cred.data = [ord(x) for x in auth["credential"]]
        current.timestamp = auth["timestamp"]

        subsequent = netr_Authenticator()
        return (current, subsequent)

    def do_NetrLogonSamLogonWithFlags(self, c, current, subsequent):
        logon = samlogon_logon_info(self.domain, self.machine_name,
                                    self.user_creds)

        logon_level = netlogon.NetlogonNetworkTransitiveInformation
        validation_level = netlogon.NetlogonValidationSamInfo4
        netr_flags = 0
        c.netr_LogonSamLogonWithFlags(self.server,
                                      self.user_creds.get_workstation(),
                                      current, subsequent, logon_level, logon,
                                      validation_level, netr_flags)

    def do_NetrLogonGetDomainInfo(self, c, current, subsequent):
        query = netr_WorkstationInformation()

        c.netr_LogonGetDomainInfo(self.server,
                                  self.user_creds.get_workstation(), current,
                                  subsequent, 2, query)
Example #53
0
class PassWordHashLDAPTests(PassWordHashTests):

    def setUp(self):
        super(PassWordHashLDAPTests, self).setUp()

    # Get the supplemental credentials for the user under test
    def get_supplemental_creds_drs(self):
        binding_str = "ncacn_ip_tcp:%s[seal]" % os.environ["SERVER"]
        dn = "cn=" + USER_NAME + ",cn=users," + self.base_dn
        drs = drsuapi.drsuapi(binding_str, self.get_loadparm(), self.creds)
        (drs_handle, supported_extensions) = drs_utils.drs_DsBind(drs)

        req8 = drsuapi.DsGetNCChangesRequest8()

        null_guid = misc.GUID()
        req8.destination_dsa_guid          = null_guid
        req8.source_dsa_invocation_id      = null_guid
        req8.naming_context                = drsuapi.DsReplicaObjectIdentifier()
        req8.naming_context.dn             = unicode(dn)

        req8.highwatermark = drsuapi.DsReplicaHighWaterMark()
        req8.highwatermark.tmp_highest_usn = 0
        req8.highwatermark.reserved_usn    = 0
        req8.highwatermark.highest_usn     = 0
        req8.uptodateness_vector           = None
        req8.replica_flags                 = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
                                              drsuapi.DRSUAPI_DRS_PER_SYNC |
                                              drsuapi.DRSUAPI_DRS_GET_ANC |
                                              drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
                                              drsuapi.DRSUAPI_DRS_WRIT_REP)
        req8.max_object_count         = 402
        req8.max_ndr_size             = 402116
        req8.extended_op              = drsuapi.DRSUAPI_EXOP_REPL_OBJ
        req8.fsmo_info                = 0
        req8.partial_attribute_set    = None
        req8.partial_attribute_set_ex = None
        req8.mapping_ctr.num_mappings = 0
        req8.mapping_ctr.mappings     = None
        (level, ctr) = drs.DsGetNCChanges(drs_handle, 8, req8)

        obj_item = ctr.first_object
        obj = obj_item.object

        sc_blob = None

        for i in range(0, obj.attribute_ctr.num_attributes):
            attr = obj.attribute_ctr.attributes[i]
            if attid_equal(attr.attid,
                           drsuapi.DRSUAPI_ATTID_supplementalCredentials):
                net_ctx = net.Net(self.creds)
                net_ctx.replicate_decrypt(drs, attr, 0)
                sc_blob = attr.value_ctr.values[0].blob


        sc = ndr_unpack(drsblobs.supplementalCredentialsBlob, sc_blob)
        return sc

    def test_wDigest_supplementalCredentials(self):
        self.creds = Credentials()
        self.creds.set_username(os.environ["USERNAME"])
        self.creds.set_password(os.environ["PASSWORD"])
        self.creds.guess(self.lp)
        ldb = SamDB("ldap://" + os.environ["SERVER"],
                    credentials=self.creds,
                    lp=self.lp)

        self.add_user(ldb=ldb)

        sc = self.get_supplemental_creds_drs()

        (pos, package) = get_package(sc, "Primary:WDigest")
        self.assertEquals("Primary:WDigest", package.name)

        # Check that the WDigest values are correct.
        #
        digests = ndr_unpack(drsblobs.package_PrimaryWDigestBlob,
                             binascii.a2b_hex(package.data))
        self.check_wdigests(digests)