Ejemplo n.º 1
0
 def setUp(self):
     super(DCKeytabTests, self).setUp()
     self.lp = LoadParm()
     self.lp.load_default()
     self.creds = self.insta_creds(template=self.get_credentials())
     self.ktfile = os.path.join(self.lp.get('private dir'), 'test.keytab')
     self.principal = self.creds.get_principal()
Ejemplo n.º 2
0
def force_drs_replication(source_dc=None,
                          destination_dc=None,
                          partition_dn=None,
                          direction="in"):
    if not package_installed('univention-samba4'):
        print(
            'force_drs_replication(): skip, univention-samba4 not installed.')
        return
    if not source_dc:
        source_dc = get_available_s4connector_dc()
        if not source_dc:
            return 1

    if not destination_dc:
        destination_dc = socket.gethostname()

    if destination_dc == source_dc:
        return

    if not partition_dn:
        lp = LoadParm()
        lp.load('/etc/samba/smb.conf')
        samdb = SamDB("tdb://%s" % lp.private_path("sam.ldb"),
                      session_info=system_session(lp),
                      lp=lp)
        partition_dn = str(samdb.domain_dn())
        print("USING partition_dn:", partition_dn)

    if direction == "in":
        cmd = ("/usr/bin/samba-tool", "drs", "replicate", destination_dc,
               source_dc, partition_dn)
    else:
        cmd = ("/usr/bin/samba-tool", "drs", "replicate", source_dc,
               destination_dc, partition_dn)
    return subprocess.call(cmd)
Ejemplo n.º 3
0
 def __init__(self, parser):
     from samba import fault_setup
     fault_setup()
     from samba.param import LoadParm
     optparse.OptionGroup.__init__(self, parser, "Samba Common Options")
     self.add_option("-s",
                     "--configfile",
                     action="callback",
                     type=str,
                     metavar="FILE",
                     help="Configuration file",
                     callback=self._load_configfile)
     self.add_option("-d",
                     "--debuglevel",
                     action="callback",
                     type=str,
                     metavar="DEBUGLEVEL",
                     help="debug level",
                     callback=self._set_debuglevel)
     self.add_option("--option",
                     action="callback",
                     type=str,
                     metavar="OPTION",
                     help="set smb.conf option from command line",
                     callback=self._set_option)
     self.add_option("--realm",
                     action="callback",
                     type=str,
                     metavar="REALM",
                     help="set the realm name",
                     callback=self._set_realm)
     self._configfile = None
     self._lp = LoadParm()
     self.realm = None
Ejemplo n.º 4
0
 def setUp(self):
     super(GPOTests, self).setUp()
     self.server = os.environ["SERVER"]
     self.dc_account = self.server.upper() + '$'
     self.lp = LoadParm()
     self.lp.load_default()
     self.creds = self.insta_creds(template=self.get_credentials())
Ejemplo n.º 5
0
class DCKeytabTests(tests.TestCase):
    def setUp(self):
        super(DCKeytabTests, self).setUp()
        self.lp = LoadParm()
        self.lp.load_default()
        self.creds = self.insta_creds(template=self.get_credentials())
        self.ktfile = os.path.join(self.lp.get('private dir'), 'test.keytab')
        self.principal = self.creds.get_principal()

    def tearDown(self):
        super(DCKeytabTests, self).tearDown()
        os.remove(self.ktfile)

    def test_export_keytab(self):
        net = Net(None, self.lp)
        net.export_keytab(keytab=self.ktfile, principal=self.principal)
        assert os.path.exists(self.ktfile), 'keytab was not created'
        with open_bytes(self.ktfile) as bytes_kt:
            result = ''
            for c in bytes_kt.read():
                if c in string.printable:
                    result += c
            principal_parts = self.principal.split('@')
            assert principal_parts[0] in result and \
                   principal_parts[1] in result, \
                        'Principal not found in generated keytab'
Ejemplo n.º 6
0
 def test_setntacl(self):
     lp = LoadParm()
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb",os.path.join(self.tempdir,"eadbtest.tdb"))
     setntacl(lp, self.tempf, acl, "S-1-5-21-2212615479-2695158682-2101375467")
     os.unlink(os.path.join(self.tempdir,"eadbtest.tdb"))
Ejemplo n.º 7
0
    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:
                os.write(w1, get_bytes(m+"\n"))
        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)
Ejemplo n.º 8
0
class DCKeytabTests(tests.TestCase):
    def setUp(self):
        super(DCKeytabTests, self).setUp()
        self.lp = LoadParm()
        self.lp.load_default()
        self.creds = self.insta_creds(template=self.get_credentials())
        self.ktfile = os.path.join(self.lp.get('private dir'), 'test.keytab')
        self.principal = self.creds.get_principal()

    def tearDown(self):
        super(DCKeytabTests, self).tearDown()
        os.remove(self.ktfile)

    def test_export_keytab(self):
        net = Net(None, self.lp)
        net.export_keytab(keytab=self.ktfile, principal=self.principal)
        assert os.path.exists(self.ktfile), 'keytab was not created'
        with open_bytes(self.ktfile) as bytes_kt:
            result = ''
            for c in bytes_kt.read():
                if c in string.printable:
                    result += c
            principal_parts = self.principal.split('@')
            assert principal_parts[0] in result and \
                principal_parts[1] in result, \
                'Principal not found in generated keytab'
Ejemplo n.º 9
0
 def test_setntacl(self):
     lp = LoadParm()
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(self.tempdir, "eadbtest.tdb"))
     setntacl(lp, self.tempf, acl,
              "S-1-5-21-2212615479-2695158682-2101375467")
     os.unlink(os.path.join(self.tempdir, "eadbtest.tdb"))
Ejemplo n.º 10
0
 def test_setntacl_forcenative(self):
     if os.getuid() == 0:
         raise SkipTest("Running test as root, test skipped")
     lp = LoadParm()
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(self.tempdir, "eadbtest.tdb"))
     self.assertRaises(Exception, setntacl, lp, self.tempf, NTACL_SDDL,
                       DOMAIN_SID, "native")
Ejemplo n.º 11
0
 def test_setntacl_forcenative(self):
     if os.getuid() == 0:
         raise SkipTest("Running test as root, test skipped")
     lp = LoadParm()
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(self.tempdir, "eadbtest.tdb"))
     self.assertRaises(Exception, setntacl, lp, self.tempf, NTACL_SDDL,
                       DOMAIN_SID, self.session_info, "native")
def _wait_for_drs_replication(ldap_filter, attrs=None, base=None, scope=ldb.SCOPE_SUBTREE, lp=None, timeout=360, delta_t=1, verbose=True, should_exist=True, controls=None):
	# type: (str, Union[List[str], None, str], Optional[str], int, Optional[LoadParm], int, int, bool, bool, Optional[List[str]]) -> None
	if not package_installed('univention-samba4'):
		if package_installed('univention-samba'):
			time.sleep(15)
			print('Sleeping 15 seconds as a workaround for http://forge.univention.org/bugzilla/show_bug.cgi?id=52145')
		elif verbose:
			print('wait_for_drs_replication(): skip, univention-samba4 not installed.')
		return
	if not attrs:
		attrs = ['dn']
	elif not isinstance(attrs, list):
		attrs = [attrs]

	if not lp:
		lp = LoadParm()
		lp.load('/etc/samba/smb.conf')
	samdb = SamDB("tdb://%s" % lp.private_path("sam.ldb"), session_info=system_session(lp), lp=lp)
	if not controls:
		controls = ["domain_scope:0"]
	if base is None:
		ucr = config_registry.ConfigRegistry()
		ucr.load()
		base = ucr['samba4/ldap/base']
	else:
		if len(ldap.dn.str2dn(base)[0]) > 1:
			if verbose:
				print('wait_for_drs_replication(): skip, multiple RDNs are not supported')
			return
	if not base:
		if verbose:
			print('wait_for_drs_replication(): skip, no samba domain found')
		return

	if verbose:
		print("Waiting for DRS replication, filter: %r, base: %r, scope: %r, should_exist: %r" % (ldap_filter, base, scope, should_exist), end=' ')
	t = t0 = time.time()
	while t < t0 + timeout:
		try:
			res = samdb.search(base=base, scope=scope, expression=ldap_filter, attrs=attrs, controls=controls)
			if bool(res) is bool(should_exist):
				if verbose:
					print("\nDRS replication took %d seconds" % (t - t0, ))
				return  # res
		except ldb.LdbError as exc:
			(_num, msg) = exc.args
			if _num == ldb.ERR_INVALID_DN_SYNTAX:
				raise
			if _num == ldb.ERR_NO_SUCH_OBJECT and not should_exist:
				if verbose:
					print("\nDRS replication took %d seconds" % (t - t0, ))
				return
			print("Error during samdb.search: %s" % (msg, ))

		print('.', end=' ')
		time.sleep(delta_t)
		t = time.time()
	raise DRSReplicationFailed("DRS replication for filter: %r failed due to timeout after %d sec." % (ldap_filter, t - t0))
Ejemplo n.º 13
0
class AuthSMB4(object):
    def __init__(self, user, password):
        self.user = user
        self.password = password
        _isLastErrorAvailable = False
        self.lp = LoadParm()
        self.lp.load_default()
        self.ip = '127.0.0.1'
        self.WorkGroup = str(self.lp.get("workgroup"))
        self.creds = credentials.Credentials()
        self.creds.set_username(self.user)
        self.creds.set_password(self.password)
        self.creds.set_domain(self.WorkGroup)
        self.creds.set_workstation("")

        self.logger = logging.getLogger(__name__)
        self.logger.addHandler(logging.StreamHandler(sys.stdout))
        self.logger.setLevel(logging.INFO)

    def Autenticate(self):
        try:
            session_info_flags = (AUTH_SESSION_INFO_DEFAULT_GROUPS
                                  | AUTH_SESSION_INFO_AUTHENTICATED)

            LdapConn = samba.Ldb("ldap://%s" % self.ip,
                                 lp=self.lp,
                                 credentials=self.creds)
            DomainDN = LdapConn.get_default_basedn()
            search_filter = "sAMAccountName=%s" % self.user
            res = LdapConn.search(base=DomainDN,
                                  scope=SCOPE_SUBTREE,
                                  expression=search_filter,
                                  attrs=["dn"])
            if len(res) == 0:
                return False

            user_dn = res[0].dn
            session = samba.auth.user_session(
                LdapConn,
                lp_ctx=self.lp,
                dn=user_dn,
                session_info_flags=session_info_flags)
            token = session.security_token

            if (token.has_builtin_administrators()):
                return True

            if (token.is_system()):
                return True

        except Exception, e:
            if (len(e.args) > 1):
                self.logger.info("%s %s" % (e.args[1], e.args[0]))
                self.SetError(e.args[1], e.args[0])
            else:
                self.logger.info("%s " % (e.args[0]))
                self.SetError(e.args, 0)
        return False
Ejemplo n.º 14
0
 def test_setntacl_forcenative(self):
     if os.getuid() == 0:
         raise SkipTest("Running test as root, test skipped")
     lp = LoadParm()
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(self.tempdir,"eadbtest.tdb"))
     self.assertRaises(Exception, setntacl, lp, self.tempf ,acl,
         "S-1-5-21-2212615479-2695158682-2101375467","native")
Ejemplo n.º 15
0
 def test_setntacl_getntacl(self):
     lp = LoadParm()
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(self.tempdir, "eadbtest.tdb"))
     setntacl(lp, self.tempf, NTACL_SDDL, DOMAIN_SID)
     facl = getntacl(lp, self.tempf)
     anysid = security.dom_sid(security.SID_NT_SELF)
     self.assertEquals(facl.as_sddl(anysid), NTACL_SDDL)
     os.unlink(os.path.join(self.tempdir, "eadbtest.tdb"))
Ejemplo n.º 16
0
 def test_setntacl_getntacl(self):
     lp = LoadParm()
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(self.tempdir, "eadbtest.tdb"))
     setntacl(lp, self.tempf, NTACL_SDDL, DOMAIN_SID, self.session_info)
     facl = getntacl(lp, self.tempf, self.session_info)
     anysid = security.dom_sid(security.SID_NT_SELF)
     self.assertEqual(facl.as_sddl(anysid), NTACL_SDDL)
     os.unlink(os.path.join(self.tempdir, "eadbtest.tdb"))
def wait_for_drs_replication(ldap_filter, attrs=None, base=None, scope=ldb.SCOPE_SUBTREE, lp=None, timeout=360, delta_t=1, verbose=True, should_exist=True, controls=None):
	if not package_installed('univention-samba4'):
		if verbose:
			print('wait_for_drs_replication(): skip, univention-samba4 not installed.')
		return
	if not lp:
		lp = LoadParm()
		lp.load('/etc/samba/smb.conf')
	if not attrs:
		attrs = ['dn']
	elif not isinstance(attrs, list):
		attrs = [attrs]

	samdb = SamDB("tdb://%s" % lp.private_path("sam.ldb"), session_info=system_session(lp), lp=lp)
	if not controls:
		controls = ["domain_scope:0"]
	if base is None:
		base = samdb.domain_dn()
	else:
		if len(ldap.dn.str2dn(base)[0]) > 1:
			if verbose:
				print('wait_for_drs_replication(): skip, multiple RDNs are not supported')
			return
	if not base or base == 'None':
		if verbose:
			print('wait_for_drs_replication(): skip, no samba domain found')
		return

	if verbose:
		print("Waiting for DRS replication, filter: %r, base: %r, scope: %r, should_exist: %r" % (ldap_filter, base, scope, should_exist), end=' ')
	t = t0 = time.time()
	while t < t0 + timeout:
		try:
			res = samdb.search(base=base, scope=scope, expression=ldap_filter, attrs=attrs, controls=controls)
			if res and should_exist:
				if verbose:
					print("\nDRS replication took %d seconds" % (t - t0, ))
				return res
			if not res and not should_exist:
				if verbose:
					print("\nDRS replication took %d seconds" % (t - t0, ))
				return res
		except ldb.LdbError as exc:
			(_num, msg) = exc.args
			if _num == ldb.ERR_INVALID_DN_SYNTAX:
				raise
			if _num == ldb.ERR_NO_SUCH_OBJECT and not should_exist:
				if verbose:
					print("\nDRS replication took %d seconds" % (t - t0, ))
				return
			print("Error during samdb.search: %s" % (msg, ))

		print('.', end=' ')
		time.sleep(delta_t)
		t = time.time()
	raise DRSReplicationFailed("DRS replication for filter: %r failed due to timeout after %d sec." % (ldap_filter, t - t0))
Ejemplo n.º 18
0
 def __init__(self):
     self.samba_lp = LoadParm()
     self.samba_lp.set('debug level', '0')
     self.samba_lp.load_default()
     url = self.samba_lp.get('dcerpc_mapiproxy:samdb_url') or \
         self.samba_lp.private_path("sam.ldb")
     self.samdb = SamDB(url=url,
                        lp=self.samba_lp,
                        session_info=system_session())
     self.conn = self._open_mysql_connection()
Ejemplo n.º 19
0
    def __init__(self, user, password):
        self.user = user
        self.password = password
        _isLastErrorAvailable = False
        self.lp = LoadParm()
        self.lp.load_default()

        self.logger = logging.getLogger(__name__)
        self.logger.addHandler(logging.StreamHandler(sys.stdout))
        self.logger.setLevel(logging.INFO)
Ejemplo n.º 20
0
 def test_setntacl_getntacl(self):
     lp = LoadParm()
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb",os.path.join(self.tempdir,"eadbtest.tdb"))
     setntacl(lp,self.tempf,acl,"S-1-5-21-2212615479-2695158682-2101375467")
     facl = getntacl(lp,self.tempf)
     anysid = security.dom_sid(security.SID_NT_SELF)
     self.assertEquals(facl.as_sddl(anysid),acl)
     os.unlink(os.path.join(self.tempdir,"eadbtest.tdb"))
Ejemplo n.º 21
0
 def test_setntacl_forcenative(self):
     if os.getuid() == 0:
         raise SkipTest("Running test as root, test skipped")
     lp = LoadParm()
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(self.tempdir, "eadbtest.tdb"))
     self.assertRaises(Exception, setntacl, lp, self.tempf, acl,
                       "S-1-5-21-2212615479-2695158682-2101375467",
                       "native")
Ejemplo n.º 22
0
def parametros(fichero=False):
    """
    Intento ser un poco cuidadoso con la forma en que obtenemos la configuración
    """
    try:
        lp = LoadParm()
        lp.load_default() if fichero is False else lp.load(fichero)
        return lp
    except RuntimeError as e:
        log.warning(e.message)
        raise ConfiguracionException(e)
Ejemplo n.º 23
0
 def test_setntacl_getntacl(self):
     lp = LoadParm()
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     open(self.tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(self.tempdir, "eadbtest.tdb"))
     setntacl(lp, self.tempf, acl,
              "S-1-5-21-2212615479-2695158682-2101375467")
     facl = getntacl(lp, self.tempf)
     anysid = security.dom_sid(security.SID_NT_SELF)
     self.assertEquals(facl.as_sddl(anysid), acl)
     os.unlink(os.path.join(self.tempdir, "eadbtest.tdb"))
Ejemplo n.º 24
0
 def __init__(self, user, password):
     self.user = user
     self.password = password
     self.lp = LoadParm()
     self.lp.load_default()
     self.ip = '127.0.0.1'
     self.WorkGroup = str(self.lp.get("workgroup"))
     self.creds = credentials.Credentials()
     self.creds.set_username(self.user)
     self.creds.set_password(self.password)
     self.creds.set_domain(self.WorkGroup)
     self.creds.set_workstation("")
Ejemplo n.º 25
0
 def test_setntacl(self):
     random.seed()
     lp = LoadParm()
     path = os.environ['SELFTEST_PREFIX']
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     tempf = os.path.join(path,"pytests"+str(int(100000*random.random())))
     ntacl = xattr.NTACL()
     ntacl.version = 1
     open(tempf, 'w').write("empty")
     lp.set("posix:eadb",os.path.join(path,"eadbtest.tdb"))
     setntacl(lp, tempf, acl, "S-1-5-21-2212615479-2695158682-2101375467")
     os.unlink(tempf)
Ejemplo n.º 26
0
def main():
    args = parse_args()
    logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING)

    inpipe = sys.stdin
    outpipe = sys.stdout

    if args.unix:
        import socket
        try:
            os.remove(args.unix)
        except OSError:
            pass

        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.bind(args.unix)
        os.chmod(args.unix, 0o777)
        logger.debug("Bound unix socket: {}".format(args.unix))

        logger.info("Waiting for connection at {}".format(args.unix))
        sock.listen(1)
        csock, client_address = sock.accept()

        logger.info("Accepted connection from {}".format(client_address))
        inpipe = outpipe = csock.makefile()

    lp = LoadParm()
    lp.load_default()

    creds = Credentials()
    creds.guess(lp)
    creds.set_kerberos_state(MUST_USE_KERBEROS)
    # If MUST_USE_KERBEROS and we have no ticket, yields this error:
    # "Failed to connect to 'ldap://dc1' with backend 'ldap': LDAP client
    # internal error: NT_STATUS_INVALID_PARAMETER"

    # lp is required by ldap_connect_send() -> lpcfg_resolve_context()
    samdb = SamDB(lp=lp, url=args.url, credentials=creds)

    logger.debug("Opened SAM DB:")
    logger.debug("  domain_dn:       {}".format(samdb.domain_dn()))
    logger.debug("  domain_dns_name: {}".format(samdb.domain_dns_name()))

    try:
        r = SambaResponder(samdb, inpipe, outpipe)
        r.run()
    finally:
        if args.unix:
            try:
                os.remove(args.unix)
            except OSError:
                pass
Ejemplo n.º 27
0
class GPOTests(tests.TestCase):
    def setUp(self):
        super(GPOTests, self).setUp()
        self.server = os.environ["SERVER"]
        self.lp = LoadParm()
        self.lp.load_default()
        self.creds = self.insta_creds(template=self.get_credentials())

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

    def test_gpo_list(self):
        global poldir, dspath
        ads = gpo.ADS_STRUCT(self.server, self.lp, self.creds)
        if ads.connect():
            gpos = ads.get_gpo_list(self.creds.get_username())
        guid = '{31B2F340-016D-11D2-945F-00C04FB984F9}'
        names = ['Local Policy', guid]
        file_sys_paths = [None, '%s\\%s' % (poldir, guid)]
        ds_paths = [None, 'CN=%s,%s' % (guid, dspath)]
        for i in range(0, len(gpos)):
            assert gpos[i].name == names[i], \
              'The gpo name did not match expected name %s' % gpos[i].name
            assert gpos[i].file_sys_path == file_sys_paths[i], \
              'file_sys_path did not match expected %s' % gpos[i].file_sys_path
            assert gpos[i].ds_path == ds_paths[i], \
              'ds_path did not match expected %s' % gpos[i].ds_path


    def test_gpo_ads_does_not_segfault(self):
        try:
            ads = gpo.ADS_STRUCT(self.server, 42, self.creds)
        except:
            pass

    def test_gpt_version(self):
        global gpt_data
        local_path = self.lp.get("path", "sysvol")
        policies = 'addom.samba.example.com/Policies'
        guid = '{31B2F340-016D-11D2-945F-00C04FB984F9}'
        gpo_path = os.path.join(local_path, policies, guid)
        old_vers = gpo.gpo_get_sysvol_gpt_version(gpo_path)[1]

        with open(os.path.join(gpo_path, 'GPT.INI'), 'w') as gpt:
            gpt.write(gpt_data % 42)
        assert gpo.gpo_get_sysvol_gpt_version(gpo_path)[1] == 42, \
          'gpo_get_sysvol_gpt_version() did not return the expected version'

        with open(os.path.join(gpo_path, 'GPT.INI'), 'w') as gpt:
            gpt.write(gpt_data % old_vers)
        assert gpo.gpo_get_sysvol_gpt_version(gpo_path)[1] == old_vers, \
          'gpo_get_sysvol_gpt_version() did not return the expected version'
Ejemplo n.º 28
0
 def test_setntacl(self):
     random.seed()
     lp = LoadParm()
     path = os.environ['SELFTEST_PREFIX']
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     tempf = os.path.join(path,
                          "pytests" + str(int(100000 * random.random())))
     ntacl = xattr.NTACL()
     ntacl.version = 1
     open(tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(path, "eadbtest.tdb"))
     setntacl(lp, tempf, acl, "S-1-5-21-2212615479-2695158682-2101375467")
     os.unlink(tempf)
Ejemplo n.º 29
0
def wait_for_drs_replication(ldap_filter,
                             attrs=None,
                             base=None,
                             scope=ldb.SCOPE_SUBTREE,
                             lp=None,
                             timeout=360,
                             delta_t=1,
                             verbose=True):
    if not package_installed('univention-samba4'):
        if verbose:
            print 'wait_for_drs_replication(): skip, univention-samba4 not installed.'
        return
    if not lp:
        lp = LoadParm()
        lp.load('/etc/samba/smb.conf')
    if not attrs:
        attrs = ['dn']
    elif not isinstance(attrs, list):
        attrs = [attrs]

    samdb = SamDB("tdb://%s" % lp.private_path("sam.ldb"),
                  session_info=system_session(lp),
                  lp=lp)
    controls = ["domain_scope:0"]
    if base is None:
        base = samdb.domain_dn()
    if not base or base == 'None':
        if verbose:
            print 'wait_for_drs_replication(): skip, no samba domain found'
        return

    if verbose:
        print "Waiting for DRS replication, filter: '%s'" % (ldap_filter, ),
    t = t0 = time.time()
    while t < t0 + timeout:
        try:
            res = samdb.search(base=base,
                               scope=scope,
                               expression=ldap_filter,
                               attrs=attrs,
                               controls=controls)
            if res:
                if verbose:
                    print "\nDRS replication took %d seconds" % (t - t0, )
                return res
        except ldb.LdbError as (_num, msg):
            print "Error during samdb.search: %s" % (msg, )

        print '.',
        time.sleep(delta_t)
        t = time.time()
Ejemplo n.º 30
0
class GPOTests(tests.TestCase):
    def setUp(self):
        super(GPOTests, self).setUp()
        self.server = os.environ["SERVER"]
        self.lp = LoadParm()
        self.lp.load_default()
        self.creds = self.insta_creds(template=self.get_credentials())

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

    def test_gpo_list(self):
        global poldir, dspath
        ads = gpo.ADS_STRUCT(self.server, self.lp, self.creds)
        if ads.connect():
            gpos = ads.get_gpo_list(self.creds.get_username())
        guid = '{31B2F340-016D-11D2-945F-00C04FB984F9}'
        names = ['Local Policy', guid]
        file_sys_paths = [None, '%s\\%s' % (poldir, guid)]
        ds_paths = [None, 'CN=%s,%s' % (guid, dspath)]
        for i in range(0, len(gpos)):
            assert gpos[i].name == names[i], \
              'The gpo name did not match expected name %s' % gpos[i].name
            assert gpos[i].file_sys_path == file_sys_paths[i], \
              'file_sys_path did not match expected %s' % gpos[i].file_sys_path
            assert gpos[i].ds_path == ds_paths[i], \
              'ds_path did not match expected %s' % gpos[i].ds_path

    def test_gpo_ads_does_not_segfault(self):
        try:
            ads = gpo.ADS_STRUCT(self.server, 42, self.creds)
        except:
            pass

    def test_gpt_version(self):
        global gpt_data
        local_path = self.lp.get("path", "sysvol")
        policies = 'addom.samba.example.com/Policies'
        guid = '{31B2F340-016D-11D2-945F-00C04FB984F9}'
        gpo_path = os.path.join(local_path, policies, guid)
        old_vers = gpo.gpo_get_sysvol_gpt_version(gpo_path)[1]

        with open(os.path.join(gpo_path, 'GPT.INI'), 'w') as gpt:
            gpt.write(gpt_data % 42)
        assert gpo.gpo_get_sysvol_gpt_version(gpo_path)[1] == 42, \
          'gpo_get_sysvol_gpt_version() did not return the expected version'

        with open(os.path.join(gpo_path, 'GPT.INI'), 'w') as gpt:
            gpt.write(gpt_data % old_vers)
        assert gpo.gpo_get_sysvol_gpt_version(gpo_path)[1] == old_vers, \
          'gpo_get_sysvol_gpt_version() did not return the expected version'
Ejemplo n.º 31
0
class Options:
	def __init__(self):
		self.function_level = None
		self.use_xattrs = "auto" 
		self.lp = LoadParm();
		self.lp.load_default();
		self.realm = self.lp.get('realm') #default
		self.domain = self.lp.get('workgroup') #default
		self.adminpass = ''
		self.smbconf = self.lp.configfile
		self.server_role = self.lp.get("server role") #default
		self.samdb_fill = FILL_FULL #default
		self.blank = False
		self.partitions_only = False
Ejemplo n.º 32
0
class AuthSMB4(object):
	def __init__(self,user,password):
		self.user = user
		self.password = password
		_isLastErrorAvailable=False
		self.lp = LoadParm()
		self.lp.load_default()
                self.ip = '127.0.0.1'
                self.WorkGroup = str(self.lp.get("workgroup"))
                self.creds = credentials.Credentials()
                self.creds.set_username(self.user)
                self.creds.set_password(self.password)
                self.creds.set_domain(self.WorkGroup)
                self.creds.set_workstation("")


		self.logger = logging.getLogger(__name__)
		self.logger.addHandler(logging.StreamHandler(sys.stdout))
		self.logger.setLevel(logging.INFO)
		
        def Autenticate(self):
                try:
                        session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS | AUTH_SESSION_INFO_AUTHENTICATED )

                        LdapConn = samba.Ldb("ldap://%s" % self.ip,lp=self.lp,credentials=self.creds)
                        DomainDN = LdapConn.get_default_basedn()
                        search_filter="sAMAccountName=%s" % self.user
                        res = LdapConn.search(base=DomainDN, scope=SCOPE_SUBTREE,expression=search_filter, attrs=["dn"])
                        if len(res) == 0:
                                return False

                        user_dn = res[0].dn
                        session = samba.auth.user_session(LdapConn, lp_ctx=self.lp, dn=user_dn,session_info_flags=session_info_flags)
                        token = session.security_token


                        if (token.has_builtin_administrators()):
                                return True

                        if(token.is_system()):
                                return True

                except Exception,e:
                        if(len(e.args)>1):
                                self.logger.info("%s %s" % (e.args[1],e.args[0]))
                                self.SetError(e.args[1],e.args[0])
                        else:
                                self.logger.info("%s " % (e.args[0]))
                                self.SetError(e.args,0)
                return False
Ejemplo n.º 33
0
 def test_setntacl_forcenative(self):
     if os.getuid() == 0:
         raise TestSkipped("Running test as root, test skipped")
     random.seed()
     lp = LoadParm()
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     path = os.environ['SELFTEST_PREFIX']
     tempf = os.path.join(path,"pytests"+str(int(100000*random.random())))
     ntacl = xattr.NTACL()
     ntacl.version = 1
     open(tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(path,"eadbtest.tdb"))
     self.assertRaises(Exception, setntacl, lp, tempf ,acl,
         "S-1-5-21-2212615479-2695158682-2101375467","native")
     os.unlink(tempf)
Ejemplo n.º 34
0
    def test_vgp_access_add(self):
        lp = LoadParm()
        lp.load(os.environ['SERVERCONFFILE'])

        (result, out, err) = self.runsublevelcmd(
            "gpo", ("manage", "access", "add"), self.gpo_guid, "allow",
            self.test_user,
            lp.get('realm').lower(), "-H", "ldap://%s" % os.environ["SERVER"],
            "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"]))
        self.assertCmdSuccess(result, out, err, 'Access add failed')

        (result, out, err) = self.runsublevelcmd(
            "gpo", ("manage", "access", "add"), self.gpo_guid, "deny",
            self.test_group,
            lp.get('realm').lower(), "-H", "ldap://%s" % os.environ["SERVER"],
            "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"]))
        self.assertCmdSuccess(result, out, err, 'Access add failed')

        allow_entry = '+:%s\\%s:ALL' % (lp.get('realm').lower(),
                                        self.test_user)
        deny_entry = '-:%s\\%s:ALL' % (lp.get('realm').lower(),
                                       self.test_group)
        (result, out, err) = self.runsublevelcmd(
            "gpo", ("manage", "access", "list"), self.gpo_guid, "-H",
            "ldap://%s" % os.environ["SERVER"],
            "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"]))
        self.assertIn(allow_entry, out, 'The test entry was not found!')
        self.assertIn(deny_entry, out, 'The test entry was not found!')

        (result, out, err) = self.runsublevelcmd(
            "gpo", ("manage", "access", "remove"), self.gpo_guid, "allow",
            self.test_user,
            lp.get('realm').lower(), "-H", "ldap://%s" % os.environ["SERVER"],
            "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"]))
        self.assertCmdSuccess(result, out, err, 'Access remove failed')
        (result, out, err) = self.runsublevelcmd(
            "gpo", ("manage", "access", "remove"), self.gpo_guid, "deny",
            self.test_group,
            lp.get('realm').lower(), "-H", "ldap://%s" % os.environ["SERVER"],
            "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"]))
        self.assertCmdSuccess(result, out, err, 'Access remove failed')

        (result, out, err) = self.runsublevelcmd(
            "gpo", ("manage", "access", "list"), self.gpo_guid, "-H",
            "ldap://%s" % os.environ["SERVER"],
            "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"]))
        self.assertNotIn(allow_entry, out, 'The test entry was still found!')
        self.assertNotIn(deny_entry, out, 'The test entry was still found!')
Ejemplo n.º 35
0
class auth_base(object):
    def __init__(self, user, password):
        self.user = user
        self.password = password
        self.lp = LoadParm()
        self.lp.load_default()
        self.ip = '127.0.0.1'
        self.WorkGroup = str(self.lp.get("workgroup"))
        self.creds = credentials.Credentials()
        self.creds.set_username(self.user)
        self.creds.set_password(self.password)
        self.creds.set_domain(self.WorkGroup)
        self.creds.set_workstation("")

    def autenticate(self):
        try:
            session_info_flags = (df_gp1 | df_gp2)

            LdapConn = samba.Ldb("ldap://%s" % self.ip,
                                 lp=self.lp,
                                 credentials=self.creds)
            DomainDN = LdapConn.get_default_basedn()
            search_filter = "sAMAccountName=%s" % self.user
            res = LdapConn.search(base=DomainDN,
                                  scope=SCOPE_SUBTREE,
                                  expression=search_filter,
                                  attrs=["dn"])
            if len(res) == 0:
                return False

            user_dn = res[0].dn
            session = samba.auth.user_session(
                LdapConn,
                lp_ctx=self.lp,
                dn=user_dn,
                session_info_flags=session_info_flags)
            token = session.security_token

            if (token.has_builtin_administrators()):
                return True

            if (token.is_system()):
                return True

        except Exception:
            return False

        return False
Ejemplo n.º 36
0
 def test_setntacl_invalidbackend(self):
     lp = LoadParm()
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     open(self.tempf, 'w').write("empty")
     self.assertRaises(XattrBackendError, setntacl, lp, self.tempf, acl,
                       "S-1-5-21-2212615479-2695158682-2101375467", "ttdb",
                       os.path.join(self.tempdir, "eadbtest.tdb"))
Ejemplo n.º 37
0
 def __init__(self, username=None, no_dry_run=False, mysql_string=None):
     self.lp = LoadParm()
     self.lp.set('debug level', '0')
     self.lp.load_default()
     self.username = username
     self.no_dry_run = no_dry_run
     self.conn = self._open_mysql_conn(mysql_string)
Ejemplo n.º 38
0
 def test_setntacl_getntacl(self):
     random.seed()
     lp = LoadParm()
     path = None
     path = os.environ['SELFTEST_PREFIX']
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     tempf = os.path.join(path,"pytests"+str(int(100000*random.random())))
     ntacl = xattr.NTACL()
     ntacl.version = 1
     open(tempf, 'w').write("empty")
     lp.set("posix:eadb",os.path.join(path,"eadbtest.tdb"))
     setntacl(lp,tempf,acl,"S-1-5-21-2212615479-2695158682-2101375467")
     facl = getntacl(lp,tempf)
     anysid = security.dom_sid(security.SID_NT_SELF)
     self.assertEquals(facl.info.as_sddl(anysid),acl)
     os.unlink(tempf)
Ejemplo n.º 39
0
 def __init__(self):
     self.samba_lp = LoadParm()
     self.samba_lp.set("debug level", "0")
     self.samba_lp.load_default()
     url = self.samba_lp.get("dcerpc_mapiproxy:samdb_url") or self.samba_lp.private_path("sam.ldb")
     self.samdb = SamDB(url=url, lp=self.samba_lp, session_info=system_session())
     self.conn = self._open_mysql_connection()
Ejemplo n.º 40
0
 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 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
Ejemplo n.º 42
0
 def setUp(self):
     super(DCKeytabTests, self).setUp()
     self.lp = LoadParm()
     self.lp.load_default()
     self.creds = self.insta_creds(template=self.get_credentials())
     self.ktfile = os.path.join(self.lp.get('private dir'), 'test.keytab')
     self.principal = self.creds.get_principal()
Ejemplo n.º 43
0
    def __init__(self, user, password):
        self.user = user
        self.password = password
        _isLastErrorAvailable = False
        self.lp = LoadParm()
        self.lp.load_default()
        self.ip = '127.0.0.1'
        self.WorkGroup = str(self.lp.get("workgroup"))
        self.creds = credentials.Credentials()
        self.creds.set_username(self.user)
        self.creds.set_password(self.password)
        self.creds.set_domain(self.WorkGroup)
        self.creds.set_workstation("")

        self.logger = logging.getLogger(__name__)
        self.logger.addHandler(logging.StreamHandler(sys.stdout))
        self.logger.setLevel(logging.INFO)
Ejemplo n.º 44
0
 def test_setntacl_getntacl(self):
     random.seed()
     lp = LoadParm()
     path = None
     path = os.environ['SELFTEST_PREFIX']
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     tempf = os.path.join(path,
                          "pytests" + str(int(100000 * random.random())))
     ntacl = xattr.NTACL()
     ntacl.version = 1
     open(tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(path, "eadbtest.tdb"))
     setntacl(lp, tempf, acl, "S-1-5-21-2212615479-2695158682-2101375467")
     facl = getntacl(lp, tempf)
     anysid = security.dom_sid(security.SID_NT_SELF)
     self.assertEquals(facl.info.as_sddl(anysid), acl)
     os.unlink(tempf)
Ejemplo n.º 45
0
 def test_setntacl_forcenative(self):
     if os.getuid() == 0:
         raise TestSkipped("Running test as root, test skipped")
     random.seed()
     lp = LoadParm()
     acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)"
     path = os.environ['SELFTEST_PREFIX']
     tempf = os.path.join(path,
                          "pytests" + str(int(100000 * random.random())))
     ntacl = xattr.NTACL()
     ntacl.version = 1
     open(tempf, 'w').write("empty")
     lp.set("posix:eadb", os.path.join(path, "eadbtest.tdb"))
     self.assertRaises(Exception, setntacl, lp, tempf, acl,
                       "S-1-5-21-2212615479-2695158682-2101375467",
                       "native")
     os.unlink(tempf)
Ejemplo n.º 46
0
 def test_admx_load(self):
     lp = LoadParm()
     lp.load(os.environ['SERVERCONFFILE'])
     local_path = lp.get('path', 'sysvol')
     admx_path = os.path.join(local_path, os.environ['REALM'].lower(),
                              'Policies', 'PolicyDefinitions')
     (result, out, err) = self.runsubcmd(
         "gpo", "admxload", "-H", "ldap://%s" % os.environ["SERVER"],
         "--admx-dir=%s" % os.path.join(source_path, 'libgpo/admx'),
         "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"]))
     self.assertCmdSuccess(result, out, err,
                           'Filling PolicyDefinitions failed')
     self.assertTrue(os.path.exists(admx_path),
                     'PolicyDefinitions was not created')
     self.assertTrue(os.path.exists(os.path.join(admx_path, 'samba.admx')),
                     'Filling PolicyDefinitions failed')
     shutil.rmtree(admx_path)
Ejemplo n.º 47
0
class SambaOCHelper(object):
    def __init__(self):
        self.samba_lp = LoadParm()
        self.samba_lp.set('debug level', '0')
        self.samba_lp.load_default()
        url = self.samba_lp.get('dcerpc_mapiproxy:samdb_url') or \
            self.samba_lp.private_path("sam.ldb")
        self.samdb = SamDB(url=url,
                           lp=self.samba_lp,
                           session_info=system_session())
        self.conn = self._open_mysql_connection()

    def _open_mysql_connection(self):
        connection_string = self.samba_lp.get('mapiproxy:openchangedb')
        if not connection_string:
            raise Exception("Not found mapiproxy:openchangedb on samba configuration")
        # mysql://openchange:password@localhost/openchange
        m = re.search(r'(?P<scheme>.+)://(?P<user>.+):(?P<pass>.+)@(?P<host>.+)/(?P<db>.+)',
                      connection_string)
        if not m:
            raise Exception("Unable to parse mapiproxy:openchangedb: %s" %
                            connection_string)
        group_dict = m.groupdict()
        if group_dict['scheme'] != 'mysql':
            raise Exception("mapiproxy:openchangedb should start with mysql:// (we got %s)",
                            group_dict['scheme'])

        conn = MySQLdb.connect(host=group_dict['host'], user=group_dict['user'],
                               passwd=group_dict['pass'], db=group_dict['db'])
        conn.autocommit(True)
        return conn

    def invalid_user(self, username):
        ret = self.samdb.search(base=self.samdb.domain_dn(),
                                scope=ldb.SCOPE_SUBTREE,
                                expression="(sAMAccountName=%s)" % ldb.binary_encode(username))
        return len(ret) != 1

    def find_email_of(self, username):
        ret = self.samdb.search(base=self.samdb.domain_dn(),
                                scope=ldb.SCOPE_SUBTREE, attrs=["mail"],
                                expression="(sAMAccountName=%s)" % ldb.binary_encode(username))
        return ret[0]["mail"][0]

    def active_openchange_users(self):
        c = self.conn.cursor()
        c.execute("SELECT name FROM mailboxes")
        return sorted([row[0] for row in c.fetchall()])

    def get_indexing_cache(self):
        memcached_server = self.samba_lp.get('mapistore:indexing_cache')
        if not memcached_server:
            return "127.0.0.1:11211"
        # This should has a format like: --SERVER=11.22.33.44:11211
        return memcached_server.split('=')[1]
Ejemplo n.º 48
0
	def __init__(self,user,password):
		self.user = user
		self.password = password
		_isLastErrorAvailable=False
		self.lp = LoadParm()
		self.lp.load_default()

		self.logger = logging.getLogger(__name__)
		self.logger.addHandler(logging.StreamHandler(sys.stdout))
		self.logger.setLevel(logging.INFO)
Ejemplo n.º 49
0
 def __init__(self):
     self.samba_lp = LoadParm()
     self.samba_lp.set('debug level', '0')
     self.samba_lp.load_default()
     self.next_fmid = None
     url = self.samba_lp.get('dcerpc_mapiproxy:samdb_url') or \
         self.samba_lp.private_path("sam.ldb")
     self.samdb = SamDB(url=url,
                        lp=self.samba_lp,
                        session_info=system_session())
     self.conn = self._open_mysql_connection()
Ejemplo n.º 50
0
    def apply(cls, cur, **kwargs):
        # Mimetise what mapistore_interface.c (mapistore_init) does
        # to get the mapping path
        if 'lp' in kwargs:
            mapping_path = kwargs['lp'].private_path("mapistore")
        else:
            lp = LoadParm()
            lp.load_default()
            mapping_path = lp.private_path("mapistore")

        if mapping_path is None:
            return

        cur.execute("START TRANSACTION")
        try:
            # Get all mailboxes
            cur.execute("SELECT name FROM mailboxes")
            for row in cur.fetchall():
                username = row[0]
                path = "{0}/{1}/replica_mapping.tdb".format(mapping_path, username)
                try:
                    tdb_file = tdb.Tdb(path, 0, tdb.DEFAULT, os.O_RDONLY)
                    for k in tdb_file.iterkeys():
                        # Check if the key is an integer
                        try:
                            repl_id = int(k, base=16)
                            cls._insert_map(cur, username, repl_id, tdb_file[k])
                        except ValueError:
                            # Cannot convert to int, so no repl_id
                            continue
                except IOError:
                    # Cannot read any replica mapping
                    continue

            cur.execute("COMMIT")
        except Exception as e:
            print("Error migrating TDB files into the database {}, rollback".format(e), file=sys.stderr)
            cur.execute("ROLLBACK")
            raise
Ejemplo n.º 51
0
class AuthBase(object):
	def __init__(self,user,password):
		self.user = user
		self.password = password
		_isLastErrorAvailable=False
		self.lp = LoadParm()
		self.lp.load_default()

		self.logger = logging.getLogger(__name__)
		self.logger.addHandler(logging.StreamHandler(sys.stdout))
		self.logger.setLevel(logging.INFO)
		
	def Autenticate(self):
		pass
	
	def SetError(self,message,number=-1):
		self.LastErrorStr = message
		self.LastErrorNumber = number
		#self.Log.LogError(message)
		self._isLastErrorAvailable=True
			
	def IHaveError(self):
		return self._isLastErrorAvailable
Ejemplo n.º 52
0
def upgrade_smbconf(oldconf,mark):
    """Remove configuration variables not present in Samba4

    :param oldconf: Old configuration structure
    :param mark: Whether removed configuration variables should be
        kept in the new configuration as "samba3:<name>"
    """
    data = oldconf.data()
    newconf = LoadParm()

    for s in data:
        for p in data[s]:
            keep = False
            for k in smbconf_keep:
                if smbconf_keep[k] == p:
                    keep = True
                    break

            if keep:
                newconf.set(s, p, oldconf.get(s, p))
            elif mark:
                newconf.set(s, "samba3:"+p, oldconf.get(s,p))

    return newconf
Ejemplo n.º 53
0
 def __init__(self, parser):
     from samba.param import LoadParm
     optparse.OptionGroup.__init__(self, parser, "Samba Common Options")
     self.add_option("-s", "--configfile", action="callback",
                     type=str, metavar="FILE", help="Configuration file",
                     callback=self._load_configfile)
     self.add_option("-d", "--debuglevel", action="callback",
                     type=int, metavar="DEBUGLEVEL", help="debug level",
                     callback=self._set_debuglevel)
     self.add_option("--option", action="callback",
                     type=str, metavar="OPTION", help="set smb.conf option from command line",
                     callback=self._set_option)
     self.add_option("--realm", action="callback",
                     type=str, metavar="REALM", help="set the realm name",
                     callback=self._set_realm)
     self._configfile = None
     self._lp = LoadParm()
Ejemplo n.º 54
0
class SambaOCHelper(object):
    def __init__(self):
        self.samba_lp = LoadParm()
        self.samba_lp.set("debug level", "0")
        self.samba_lp.load_default()
        url = self.samba_lp.get("dcerpc_mapiproxy:samdb_url") or self.samba_lp.private_path("sam.ldb")
        self.samdb = SamDB(url=url, lp=self.samba_lp, session_info=system_session())
        self.conn = self._open_mysql_connection()

    def _open_mysql_connection(self):
        connection_string = self.samba_lp.get("mapiproxy:openchangedb")
        if not connection_string:
            raise Exception("Not found mapiproxy:openchangedb on samba configuration")
        # mysql://openchange:password@localhost/openchange
        m = re.search(r"(?P<scheme>.+)://(?P<user>.+):(?P<pass>.+)@(?P<host>.+)/(?P<db>.+)", connection_string)
        if not m:
            raise Exception("Unable to parse mapiproxy:openchangedb: %s" % connection_string)
        group_dict = m.groupdict()
        if group_dict["scheme"] != "mysql":
            raise Exception("mapiproxy:openchangedb should start with mysql:// (we got %s)", group_dict["scheme"])

        conn = MySQLdb.connect(
            host=group_dict["host"], user=group_dict["user"], passwd=group_dict["pass"], db=group_dict["db"]
        )
        conn.autocommit(True)
        return conn

    def invalid_user(self, username):
        ret = self.samdb.search(
            base=self.samdb.domain_dn(),
            scope=ldb.SCOPE_SUBTREE,
            expression="(sAMAccountName=%s)" % ldb.binary_encode(username),
        )
        return len(ret) != 1

    def find_email_of(self, username):
        ret = self.samdb.search(
            base=self.samdb.domain_dn(),
            scope=ldb.SCOPE_SUBTREE,
            attrs=["mail"],
            expression="(sAMAccountName=%s)" % ldb.binary_encode(username),
        )
        return ret[0]["mail"][0]

    def active_openchange_users(self):
        c = self.conn.cursor()
        c.execute("SELECT name FROM mailboxes")
        return sorted([row[0] for row in c.fetchall()])
Ejemplo n.º 55
0
	def __init__(self,user,password):
		self.user = user
		self.password = password
		_isLastErrorAvailable=False
		self.lp = LoadParm()
		self.lp.load_default()
                self.ip = '127.0.0.1'
                self.WorkGroup = str(self.lp.get("workgroup"))
                self.creds = credentials.Credentials()
                self.creds.set_username(self.user)
                self.creds.set_password(self.password)
                self.creds.set_domain(self.WorkGroup)
                self.creds.set_workstation("")


		self.logger = logging.getLogger(__name__)
		self.logger.addHandler(logging.StreamHandler(sys.stdout))
		self.logger.setLevel(logging.INFO)
Ejemplo n.º 56
0
class SambaOptions(optparse.OptionGroup):
    """General Samba-related command line options."""

    def __init__(self, parser):
        from samba.param import LoadParm
        optparse.OptionGroup.__init__(self, parser, "Samba Common Options")
        self.add_option("-s", "--configfile", action="callback",
                        type=str, metavar="FILE", help="Configuration file",
                        callback=self._load_configfile)
        self.add_option("-d", "--debuglevel", action="callback",
                        type=int, metavar="DEBUGLEVEL", help="debug level",
                        callback=self._set_debuglevel)
        self.add_option("--option", action="callback",
                        type=str, metavar="OPTION",
                        help="set smb.conf option from command line",
                        callback=self._set_option)
        self.add_option("--realm", action="callback",
                        type=str, metavar="REALM", help="set the realm name",
                        callback=self._set_realm)
        self._configfile = None
        self._lp = LoadParm()
        self.realm = None

    def get_loadparm_path(self):
        """Return path to the smb.conf file specified on the command line."""
        return self._configfile

    def _load_configfile(self, option, opt_str, arg, parser):
        self._configfile = arg

    def _set_debuglevel(self, option, opt_str, arg, parser):
        if arg < 0:
            raise optparse.OptionValueError("invalid %s option value: %s" %
                                            (opt_str, arg))
        self._lp.set('debug level', str(arg))

    def _set_realm(self, option, opt_str, arg, parser):
        self._lp.set('realm', arg)
        self.realm = arg

    def _set_option(self, option, opt_str, arg, parser):
        if arg.find('=') == -1:
            raise optparse.OptionValueError(
                "--option option takes a 'a=b' argument")
        a = arg.split('=')
        try:
            self._lp.set(a[0], a[1])
        except Exception, e:
            raise optparse.OptionValueError(
                "invalid --option option value %r: %s" % (arg, e))
Ejemplo n.º 57
0
import ldb
from samba.ndr import ndr_pack, ndr_unpack
from samba.dcerpc import security
from samba.idmap import IDmapDB
from samba.auth import system_session
from samba.param import LoadParm

name='samba4-idmap'
description='Update local IDmap entries'
filter='(&(|(objectClass=sambaSamAccount)(objectClass=sambaGroupMapping))(sambaSID=*))'
attributes=['sambaSID', 'univentionSamba4SID', 'uidNumber', 'gidNumber']
modrdn='1'

### Globals
lp = LoadParm()
lp.load('/etc/samba/smb.conf')

sidAttribute='sambaSID'
if listener.configRegistry.is_false('connector/s4/mapping/sid', False):
	sidAttribute='univentionSamba4SID'


def open_idmap():
	global lp
	listener.setuid(0)
	try:
		idmap = IDmapDB('/var/lib/samba/private/idmap.ldb', session_info=system_session(), lp=lp)
	except ldb.LdbError:
		univention.debug.debug(univention.debug.LISTENER, univention.debug.ERROR,
				"%s: /var/lib/samba/private/idmap.ldb could not be opened" % name )
Ejemplo n.º 58
0
class MigrationFix(object):
    def __init__(self, username=None, no_dry_run=False, mysql_string=None):
        self.lp = LoadParm()
        self.lp.set('debug level', '0')
        self.lp.load_default()
        self.username = username
        self.no_dry_run = no_dry_run
        self.conn = self._open_mysql_conn(mysql_string)

    def _open_mysql_conn(self, mysql_conn):
        if mysql_conn is None:
            conn_str = self.lp.get('mapiproxy:openchangedb')
        else:
            conn_str = mysql_conn
        if not conn_str:
            raise Exception("No mysql connection string specified and no mapiproxy:openchangedb param option found")
        # mysql://openchange:password@localhost/openchange
        m = re.search('(?P<scheme>.+)://(?P<user>.+):(?P<pass>.+)@'
                      '(?P<host>.+)/(?P<db>.+)',
                      conn_str)
        if not m:
            raise Exception("Unable to parse mysql connection string: %s" % conn_str)
        group_dict = m.groupdict()
        if group_dict['scheme'] != 'mysql':
            raise Exception("mysql connection string should start with mysql:// (got %s)", group_dict['scheme'])
        conn = MySQLdb.connect(host=group_dict['host'], user=group_dict['user'],
                               passwd=group_dict['pass'], db=group_dict['db'])
        conn.autocommit(True)
        return conn

    def fix(self, username, folder_id, uri, mailbox_id, ou_id):
        error = False
        c = self.conn.cursor()
        c.execute("SELECT fmid FROM mapistore_indexing WHERE username=%s AND url=%s", (username,uri))
	result = c.fetchone()
	if result is None:
		print '[KO]: %s: could not find fmid for %s' % (username, uri)
		return True

        fmid = result[0]
        if str(fmid) != str(folder_id):
            error = True
            if self.no_dry_run is True:
                c = self.conn.cursor()
                c.execute("UPDATE folders SET folder_id=%s WHERE MAPIStoreURI=%s AND mailbox_id=%s AND ou_id=%s", (fmid, uri, mailbox_id, ou_id))
                print '[FIX]: %s: folder_id for %s has been fixed and is now set to %s' % (username, uri, folder_id)
            else:
                print '[KO]: %s: Mismatch for %s: found %s, expected %s' % (username, uri, folder_id, fmid)
        return error

    def run_all(self):
        c = self.conn.cursor()
        c.execute("SELECT id,ou_id,name FROM mailboxes")
        rows = c.fetchall()

        for row in rows:
            mailbox_id = row[0]
            ou_id = row[1]
            username = row[2]
            # Retrieve all MAPIStoreURI from folders table for username
            c = self.conn.cursor()
            c.execute("SELECT folder_id,MAPIStoreURI FROM folders WHERE mailbox_id=%s AND ou_id=%s AND MAPIStoreURI!=\"\"", (mailbox_id,ou_id))
            frows = c.fetchall()

            # Now check in mapistore_indexing if fmid are matching for given URI
	    gl_error =  False 
            for frow in frows:
                folder_id = frow[0]
                uri = frow[1]
                error = self.fix(username, folder_id, uri, mailbox_id, ou_id)
		if error is True:
			gl_error = True 
            if gl_error is False:
                print '[OK]: %s is OK' % (username)

    def run(self):
        # Retrieve username id, ou_id
        c = self.conn.cursor()
        c.execute("SELECT id,ou_id FROM mailboxes WHERE name=%s", self.username)
        (mailbox_id,ou_id) = c.fetchone()

        # Retrieve all MAPIStoreURI from folders table for username
        c = self.conn.cursor()
        c.execute("SELECT folder_id,MAPIStoreURI FROM folders WHERE mailbox_id=%s AND ou_id=%s AND MAPIStoreURI!=\"\"", (mailbox_id,ou_id))
        rows = c.fetchall()

        # Now check in mapistore_indexing if fmid are matching for given URI
        for row in rows:
            folder_id = row[0]
            uri = row[1]
            self.fix(self.username, folder_id, uri, mailbox_id, ou_id)
Ejemplo n.º 59
0
class SambaOCHelper(object):
    def __init__(self):
        self.samba_lp = LoadParm()
        self.samba_lp.set('debug level', '0')
        self.samba_lp.load_default()
        self.next_fmid = None
        url = self.samba_lp.get('dcerpc_mapiproxy:samdb_url') or \
            self.samba_lp.private_path("sam.ldb")
        self.samdb = SamDB(url=url,
                           lp=self.samba_lp,
                           session_info=system_session())
        self.conn = self._open_mysql_connection()

    def _open_mysql_connection(self):
        connection_string = self.samba_lp.get('mapiproxy:openchangedb')
        if not connection_string:
            raise Exception("Not found mapiproxy:openchangedb on samba configuration")
        # mysql://openchange:password@localhost/openchange
        m = re.search(r'(?P<scheme>.+)://(?P<user>.+):(?P<pass>.+)@(?P<host>.+)/(?P<db>.+)',
                      connection_string)
        if not m:
            raise Exception("Unable to parse mapiproxy:openchangedb: %s" %
                            connection_string)
        group_dict = m.groupdict()
        if group_dict['scheme'] != 'mysql':
            raise Exception("mapiproxy:openchangedb should start with mysql:// (we got %s)",
                            group_dict['scheme'])

        conn = MySQLdb.connect(host=group_dict['host'], user=group_dict['user'],
                               passwd=group_dict['pass'], db=group_dict['db'])
        conn.autocommit(True)
        return conn

    def invalid_user(self, username):
        ret = self.samdb.search(base=self.samdb.domain_dn(),
                                scope=ldb.SCOPE_SUBTREE,
                                expression="(sAMAccountName=%s)" % ldb.binary_encode(username))
        return len(ret) != 1

    def find_email_of(self, username):
        ret = self.samdb.search(base=self.samdb.domain_dn(),
                                scope=ldb.SCOPE_SUBTREE, attrs=["mail"],
                                expression="(sAMAccountName=%s)" % ldb.binary_encode(username))
        return ret[0]["mail"][0]

    def active_openchange_users(self):
        c = self.conn.cursor()
        c.execute("SELECT name FROM mailboxes")
        return sorted([row[0] for row in c.fetchall()])

    def allocate_fmids(self, count, username):
        if self.next_fmid is None:
            c = self.conn.cursor()
            c.execute("SELECT next_fmid FROM mapistore_indexes WHERE username = '******'" % username)
            self.next_fmid = c.fetchone()[0]
        if self.next_fmid is not None:
            self.next_fmid = int(self.next_fmid) + count

        return (int(self.next_fmid) - count, self.next_fmid)

    def create_indexes(self, username):
        c = self.conn.cursor()
        c.execute("INSERT INTO mapistore_indexes (username,next_fmid) VALUES('%s','1024')" % (username))
        return

    def commit_start(self):
        self.conn.autocommit(False)

    def insert_indexing(self, username, fmid, url):
        c = self.conn.cursor()
        
        c.execute("INSERT INTO mapistore_indexing (username,fmid,url,soft_deleted) VALUES('%s','%s','%s', '0')" % (username, str(fmid), url))

    def update_indexes(self, count, username):
        c = self.conn.cursor()
        updated_number = int(count) + int(self.next_fmid)
        print "Updating next_fmid to %s" % str(updated_number)
        c.execute("UPDATE mapistore_indexes SET next_fmid='%s' WHERE username='******'" % (str(updated_number), username))

    def commit_end(self):
        c = self.conn.cursor()
        self.conn.commit()
        c.close()
        self.conn.autocommit(True)
Ejemplo n.º 60
0
class SambaOptions(optparse.OptionGroup):
    """General Samba-related command line options."""

    def __init__(self, parser):
        from samba.param import LoadParm
        optparse.OptionGroup.__init__(self, parser, "Samba Common Options")
        self.add_option("-s", "--configfile", action="callback",
                        type=str, metavar="FILE", help="Configuration file",
                        callback=self._load_configfile)
        self.add_option("-d", "--debuglevel", action="callback",
                        type=int, metavar="DEBUGLEVEL", help="debug level",
                        callback=self._set_debuglevel)
        self.add_option("--option", action="callback",
                        type=str, metavar="OPTION", help="set smb.conf option from command line",
                        callback=self._set_option)
        self.add_option("--realm", action="callback",
                        type=str, metavar="REALM", help="set the realm name",
                        callback=self._set_realm)
        self._configfile = None
        self._lp = LoadParm()

    def get_loadparm_path(self):
        """Return the path to the smb.conf file specified on the command line.  """
        return self._configfile

    def _load_configfile(self, option, opt_str, arg, parser):
        self._configfile = arg

    def _set_debuglevel(self, option, opt_str, arg, parser):
        self._lp.set('debug level', str(arg))

    def _set_realm(self, option, opt_str, arg, parser):
        self._lp.set('realm', arg)

    def _set_option(self, option, opt_str, arg, parser):
        if arg.find('=') == -1:
            print("--option takes a 'a=b' argument")
            sys.exit(1)
        a = arg.split('=')
        self._lp.set(a[0], a[1])

    def get_loadparm(self):
        """Return a loadparm object with data specified on the command line.  """
        if self._configfile is not None:
            self._lp.load(self._configfile)
        elif os.getenv("SMB_CONF_PATH") is not None:
            self._lp.load(os.getenv("SMB_CONF_PATH"))
        else:
            self._lp.load_default()
        return self._lp

    def get_hostconfig(self):
        return Hostconfig(self.get_loadparm())