コード例 #1
0
ファイル: ntacls.py プロジェクト: sYnfo/samba
 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"))
コード例 #2
0
ファイル: ntacls.py プロジェクト: Alexander--/samba
 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")
コード例 #3
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"))
コード例 #4
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")
コード例 #5
0
ファイル: ntacls.py プロジェクト: Alexander--/samba
 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"))
コード例 #6
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"))
コード例 #7
0
ファイル: ntacls.py プロジェクト: sYnfo/samba
 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")
コード例 #8
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()])
コード例 #9
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")
コード例 #10
0
ファイル: ntacls.py プロジェクト: sYnfo/samba
 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"))
コード例 #11
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]
コード例 #12
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"))
コード例 #13
0
ファイル: ntacls.py プロジェクト: sprymak/samba
 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)
コード例 #14
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)
コード例 #15
0
ファイル: ntacls.py プロジェクト: sprymak/samba
 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)
コード例 #16
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()])
コード例 #17
0
ファイル: ntacls.py プロジェクト: sprymak/samba
 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)
コード例 #18
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)
コード例 #19
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)
コード例 #20
0
ファイル: getopt.py プロジェクト: encukou/samba
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 as e:
            raise optparse.OptionValueError(
                "invalid --option option value %r: %s" % (arg, e))

    def get_loadparm(self):
        """Return 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
コード例 #21
0
ファイル: getopt.py プロジェクト: reqa/samba
class SambaOptions(optparse.OptionGroup):
    """General Samba-related command line options."""

    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

    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):
        self._lp.set('debug level', arg)
        parser.values.debuglevel = 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 as e:
            raise optparse.OptionValueError(
                "invalid --option option value %r: %s" % (arg, e))

    def get_loadparm(self):
        """Return 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
コード例 #22
0
    def nested_testcase(self, backend):
        self.prov_dir = self.provision(backend)
        self.extract_dir = None

        src = os.path.join(self.prov_dir, "private")
        dst = os.path.join(self.prov_dir, "state", "private")

        # Move private directory inside state directory
        shutil.move(src, dst)

        smbconf = os.path.join(self.prov_dir, "etc", "smb.conf")

        # Update the conf file
        lp = LoadParm(filename_for_non_global_lp=smbconf)
        lp.set("private dir", dst)
        lp.dump(False, smbconf)

        backup_file = self.backup(self.prov_dir)

        # Ensure each file is only present once in the tar file
        tf = tarfile.open(backup_file)
        names = tf.getnames()
        self.assertEqual(len(names), len(set(names)))
コード例 #23
0
ファイル: upgrade.py プロジェクト: Alexandr-Galko/samba
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
コード例 #24
0
ファイル: upgrade.py プロジェクト: zhaowensky/samba-iOS
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
コード例 #25
0
class AdminToolsTestCase(unittest.TestCase):
    def assertSeen(self, what, msg=None, timeout=10):
        try:
            self.at.await_text(what, timeout=timeout)
        except hecate.hecate.Timeout:
            pass
        self.assertRegex(self.at.screenshot(), what, msg)

    def assertNotSeen(self, what, msg=None, timeout=10):
        sleep(.5)
        slept = 0
        while slept < timeout:
            slept += .1
            if not re.search(what, self.at.screenshot()):
                break
            sleep(.1)
        self.assertNotRegex(self.at.screenshot(), what, msg)

    def press(self, msg):
        self.at.press(msg)
        sleep(.1)

    def __validate_kinit(self):
        out, _ = Popen(['klist'], stdout=PIPE, stderr=PIPE).communicate()
        m = re.findall(six.b('Ticket cache:\s*(.*)'), out)
        if len(m) != 1:
            return False
        self.creds.set_named_ccache(m[0].decode())
        m = re.findall(six.b('Default principal:\s*(\w+)@([\w\.]+)'), out)
        if len(m) == 0:
            return False
        user, realm = m[0]
        self.creds.set_username(user.decode())
        self.creds.set_domain(realm.decode())
        with Popen(['klist', '-s'], stdout=PIPE, stderr=PIPE) as p:
            if p.wait() != 0:
                return False
        self.creds.set_kerberos_state(MUST_USE_KERBEROS)
        return True

    def get_password(self):
        if not self.creds.get_password():
            self.creds.set_password(
                getpass('Password for %s: ' % self.creds.get_username()))
        return self.creds.get_password()

    def kinit(self):
        while not self.__validate_kinit():
            print(
                'Domain administrator credentials are required to run the test.'
            )
            upn = '%s@%s' % (self.creds.get_username(), self.creds.get_domain(
            )) if self.creds.get_username() and self.creds.get_domain(
            ) else None
            username = input('Domain user principal name%s: ' %
                             (' (%s)' % upn if upn else ''))
            if username:
                self.creds.set_username(username)
            else:
                self.creds.set_username(upn)
            self.creds.set_password(
                getpass('Password for %s: ' % self.creds.get_username()))
            kinit_for_gssapi(self.creds, None)

    def setUp(self):
        self.lp = LoadParm()
        try:
            self.lp.load_default()
        except RuntimeError:
            pass
        self.creds = Credentials()
        self.config = ConfigParser()
        self.config.read('.tcreds')
        if self.config.has_section('creds'):
            self.creds.set_username('%s@%s' % (self.config.get(
                'creds', 'username'), self.config.get('creds', 'domain')))
            self.creds.set_domain(self.config.get('creds', 'domain'))
            self.creds.set_password(self.config.get('creds', 'password'))
            kinit_for_gssapi(self.creds, None)
        self.kinit()
        self.lp.set('realm', self.creds.get_domain())
        self.at = hecate.Runner("admin-tools", width=120, height=50)

    def tearDown(self):
        self.at.shutdown()
        if self.creds.get_password():
            if not self.config.has_section('creds'):
                self.config.add_section('creds')
            self.config.set('creds', 'username', self.creds.get_username())
            self.config.set('creds', 'domain', self.creds.get_domain())
            self.config.set('creds', 'password', self.creds.get_password())
            with open('.tcreds', 'w') as w:
                self.config.write(w)
コード例 #26
0
ファイル: migration_fix.py プロジェクト: ThHirsch/openchange
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)
コード例 #27
0
ファイル: ntacls.py プロジェクト: Alexander--/samba
 def test_setntacl(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)
     os.unlink(os.path.join(self.tempdir, "eadbtest.tdb"))
コード例 #28
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)
コード例 #29
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)
コード例 #30
0
 def test_setntacl(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)
     os.unlink(os.path.join(self.tempdir, "eadbtest.tdb"))
コード例 #31
0
ファイル: getopt.py プロジェクト: fendouzhe660/dd-wrt
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())