示例#1
0
    def test_global_loadparm(self):
        # create 2 different Loadparm objects (which are really the same
        # object underneath)
        lp1 = param.LoadParm()
        lp2 = param.LoadParm()

        # we can prove this by setting a value on lp1 and assert that the
        # change is also reflected on lp2
        lp1_realm = "JUST.A.TEST"
        self.assertNotEqual(lp2.get('realm'), lp1_realm)
        lp1.set('realm', lp1_realm)
        self.assertEqual(lp1.get('realm'), lp1_realm)
        self.assertEqual(lp2.get('realm'), lp1_realm)
示例#2
0
def env_loadparm():
    lp = param.LoadParm()
    try:
        lp.load(os.environ["SMB_CONF_PATH"])
    except KeyError:
        raise KeyError("SMB_CONF_PATH not set")
    return lp
示例#3
0
    def __init__(self):
        """ Initialization """
        me = request.environ['pylons.routes_dict']['controller']
        action = request.environ['pylons.routes_dict']['action']

        log.debug("Controller: " + me)
        log.debug("Action: " + action)

        if (request.environ['pylons.routes_dict'].has_key("subaction")):
            action = request.environ['pylons.routes_dict']['subaction'] + action

        c.config = ControllerConfiguration(me, action)

        c.breadcrumb = BreadcrumbTrail(c.config)
        c.breadcrumb.build()

        c.samba_lp = param.LoadParm()
        c.samba_lp.load_default()

        self.__manager = SAMPipeManager(c.samba_lp)

        domains = self.__manager.fetch_and_get_domain_names()
        self.__manager.set_current_domain(0)
        self.__manager.fetch_users_and_groups()

        # FIXME just so that options may work
        c.current_page = int(request.params.get("page", 1))
        c.per_page = int(request.params.get("per_page", 10))
        c.filter_name = request.params.get("filter_value", "")
        c.filter_status = int(request.params.get("filter_status", -1))
示例#4
0
    def setUp(self):
        # Load MySQL configuration from default, if it does not work, try with Samba Conf
        try:
            self.db = MySQLdb.connect(host=OC_TESTSUITE_MYSQL['HOST'],
                                      user=OC_TESTSUITE_MYSQL['USER'],
                                      passwd=OC_TESTSUITE_MYSQL['PASS'])
            self.db_name = OC_TESTSUITE_MYSQL['DB']
        except:
            lp = param.LoadParm()
            lp.load_default()
            self.db = MySQLdb.connect(host=lp.get('namedproperties:mysql_host'),
                                      user=lp.get('namedproperties:mysql_user'),
                                      passwd=lp.get('namedproperties:mysql_pass'))
            self.db_name = lp.get('namedproperties:mysql_db')

        cur = self.db.cursor()
        # Ignore database exists warnings
        filterwarnings(
            action="ignore",
            category=MySQLdb.Warning,
            message="Can't create database '{}'; database exists".format(self.db_name))
        cur.execute('CREATE DATABASE IF NOT EXISTS {}'.format(self.db_name))
        self.db.commit()
        cur.close()
        self.app = 'test'
示例#5
0
 def test_provision(self):
     lp = param.LoadParm()
     lp.load_default()
     lp.set("private dir", self.tempdir)
     openchangedb_provision(lp)
     shutil.rmtree(os.path.join(self.tempdir, "mapistore"))
     os.unlink(os.path.join(self.tempdir, "openchange.ldb"))
示例#6
0
    def __perform_authentication(self, username, password):
        """ Performs User Authentication
        
        Keyword arguments:
        username -- username provided by the login form
        password -- password provided by the login form
        
        """
        from samba import credentials, param

        auth_success = False

        lp = param.LoadParm()
        lp.load_default()

        creds = credentials.Credentials()
        creds.set_username(username)
        creds.set_password(password)
        creds.set_domain("")

        if request.environ.has_key("REMOTE_HOST"):
            creds.set_workstation(request.environ.get("REMOTE_HOST"))
        else:
            creds.set_workstation("")

        auth_success = self.__auth_samr(lp, creds)
        log.info("using samr authentication")

        return auth_success
示例#7
0
    def __retrieve_trusted_domain_gc_list(self, domain):
        """
        Retrieves domain information and preferred GC list
        Returns dictionary with following keys
             name       -- NetBIOS name of the trusted domain
             dns_domain -- DNS name of the trusted domain
             auth       -- encrypted credentials for trusted domain account
             gc         -- array of tuples (server, port) for Global Catalog
        """
        if domain in self._info:
            return self._info[domain]

        if not self._creds:
            self._parm = param.LoadParm()
            self._parm.load(os.path.join(ipautil.SHARE_DIR, "smb.conf.empty"))
            self._parm.set('netbios name', self.flatname)
            self._creds = credentials.Credentials()
            self._creds.set_kerberos_state(credentials.MUST_USE_KERBEROS)
            self._creds.guess(self._parm)
            self._creds.set_workstation(self.flatname)

        netrc = net.Net(creds=self._creds, lp=self._parm)
        finddc_error = None
        result = None
        try:
            result = netrc.finddc(domain=domain,
                                  flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_GC
                                  | nbt.NBT_SERVER_CLOSEST)
        except RuntimeError, e:
            finddc_error = e
示例#8
0
 def test_provision(self):
     lp = param.LoadParm()
     lp.load_default()
     lp.set("private dir", self.tempdir)
     names = guess_names_from_smbconf(lp, firstorg="bar", firstou="foo")
     openchangedb_provision(names, lp)
     os.unlink(os.path.join(self.tempdir, "openchange.ldb"))
     os.unlink(os.path.join(self.tempdir, "sam.ldb"))
示例#9
0
 def _get_smb_connection(self, service='SysVol'):
     # Connect to SMB using kerberos
     parm = param.LoadParm()
     creds = Credentials()
     creds.set_kerberos_state(MUST_USE_KERBEROS)
     creds.guess(parm)
     conn = smb.SMB(self._get_server_name(), service, lp=parm, creds=creds)
     return conn
示例#10
0
 def test_dump_a_parameter_to_file(self):
     samba_lp = param.LoadParm()
     samba_lp.load_default()
     self.assertEqual(
         None, samba_lp.dump_a_parameter('interfaces', 'global',
                                         self.tempf))
     content = open(self.tempf, 'r').read()
     self.assertIn('127.0.0.', content)
示例#11
0
    def setUp(self):
        super(SamDBTestCase, self).setUp()
        invocationid = str(uuid.uuid4())
        domaindn = "DC=COM,DC=EXAMPLE"
        self.domaindn = domaindn
        configdn = "CN=Configuration," + domaindn
        schemadn = "CN=Schema," + configdn
        domainguid = str(uuid.uuid4())
        policyguid = str(uuid.uuid4())
        domainsid = security.random_sid()
        hostguid = str(uuid.uuid4())
        path = os.path.join(self.tempdir, "samdb.ldb")
        session_info = system_session()

        hostname = "foo"
        domain = "EXAMPLE"
        dnsdomain = "example.com"
        serverrole = "domain controller"

        smbconf = os.path.join(self.tempdir, "smb.conf")
        make_smbconf(smbconf, self.setup_path, hostname, domain, dnsdomain,
                     serverrole, self.tempdir)

        self.lp = param.LoadParm()
        self.lp.load(smbconf)

        names = guess_names(lp=self.lp,
                            hostname=hostname,
                            domain=domain,
                            dnsdomain=dnsdomain,
                            serverrole=serverrole,
                            domaindn=self.domaindn,
                            configdn=configdn,
                            schemadn=schemadn)

        paths = provision_paths_from_lp(self.lp, names.dnsdomain)

        provision_backend = ProvisionBackend("ldb",
                                             backend_type,
                                             paths=paths,
                                             setup_path=self.setup_path,
                                             lp=self.lp,
                                             credentials=None,
                                             names=names,
                                             message=message,
                                             hostname=hostname,
                                             root=root,
                                             schema=schema,
                                             domainsid=domainsid)

        self.samdb = setup_samdb(path, self.setup_path, session_info,
                                 provision_backend, self.lp, names,
                                 lambda x: None, domainsid, domainguid,
                                 policyguid, False, "secret", "secret",
                                 "secret", invocationid, "secret",
                                 "domain controller")
示例#12
0
    def conectar(self):
        lp = param.LoadParm()
        badge = Credentials()
        badge.guess(lp)

        badge.set_username(self.username)
        badge.set_password(self.password)
        cx = SamDB(url='ldap://localhost', lp=lp, credentials=badge)
        self.domain = cx.domain_dn()
        return cx
示例#13
0
 def __init__(self, hostname, creds=None):
     self.parm = param.LoadParm()
     self.parm.load(os.path.join(ipautil.SHARE_DIR, "smb.conf.empty"))
     if len(hostname) > 0:
         self.parm.set('netbios name', hostname)
     self.creds = creds
     self.hostname = hostname
     self.info = {}
     self._pipe = None
     self._policy_handle = None
     self.read_only = False
示例#14
0
    def test_non_global_loadparm(self):
        # create a empty smb.conf file
        smb_conf = self.touch_temp_file("smb.conf")

        # we can create a non-global Loadparm that overrides the default
        # behaviour and creates a separate underlying object
        lp1 = param.LoadParm()
        lp2 = param.LoadParm(filename_for_non_global_lp=smb_conf)

        # setting a value for the global LP does not affect the non-global LP
        lp1_realm = "JUST.A.TEST"
        self.assertNotEqual(lp2.get('realm'), lp1_realm)
        lp1.set('realm', lp1_realm)
        self.assertEqual(lp1.get('realm'), lp1_realm)
        self.assertNotEqual(lp2.get('realm'), lp1_realm)

        # and vice versa
        lp2_realm = "TEST.REALM.LP2"
        lp2.set('realm', lp2_realm)
        self.assertEqual(lp2.get('realm'), lp2_realm)
        self.assertEqual(lp1.get('realm'), lp1_realm)
示例#15
0
    def create_backend_object(self, params=None):
        file = config["backend.testfiles"] + config["backend.classic.testfile"]

        samba_lp = param.LoadParm()
        samba_lp.load(file)

        if params is None:
            params = {}
            params["share_path"] = "/usr/local/path"
            params["share_hosts_allow"] = "a,b,c,d"

        return share.ShareBackendClassic(samba_lp, params)
示例#16
0
    def __init__(self):
        """ """
        me = request.environ['pylons.routes_dict']['controller']
        action = request.environ['pylons.routes_dict']['action']

        c.config = ControllerConfiguration(me, action)

        c.breadcrumb = BreadcrumbTrail(c.config)
        c.breadcrumb.build()

        c.samba_lp = param.LoadParm()
        c.samba_lp.load_default()
示例#17
0
    def create_backend_object(self, params=None):
        samba_lp = param.LoadParm()
        samba_lp.load_default()

        file = config["backend.testfiles"] + config[
            "backend.ldb.clean.testfile"]

        if params is None:
            params = {}
            params["share_path"] = "/usr/local/path"
            params["share_hosts_allow"] = "a,b,c,d"

        return share.ShareBackendLdb(samba_lp, params, file)
示例#18
0
文件: smb.py 项目: tejp/freenas
 def getparm(self, parm, section):
     """
     Get a parameter from the smb4.conf file. This is more reliable than
     'testparm --parameter-name'. testparm will fail in a variety of
     conditions without returning the parameter's value.
     """
     try:
         res = param.LoadParm('/usr/local/etc/smb4.conf').get(parm, section)
         return res
     except Exception as e:
         raise CallError(
             f'Attempt to query smb4.conf parameter [{parm}] failed with error: {e}'
         )
示例#19
0
    def __init__(self):
        me = request.environ['pylons.routes_dict']['controller']
        type = request.environ['pylons.routes_dict']['action']

        c.config = ControllerConfiguration(me, type)

        c.dash = DashboardConfiguration()
        c.dash.load_config(type)

        c.breadcrumb = BreadcrumbTrail(c.config)
        c.breadcrumb.build()

        c.samba_lp = param.LoadParm()
        c.samba_lp.load_default()
示例#20
0
文件: smb.py 项目: nichoice/freenas
    def getparm(self, parm, section):
        """
        Get a parameter from the smb4.conf file. This is more reliable than
        'testparm --parameter-name'. testparm will fail in a variety of
        conditions without returning the parameter's value.
        """
        try:
            if section.upper() == 'GLOBAL':
                return param.LoadParm(SMBPath.GLOBALCONF.platform()).get(parm, section)
            else:
                return self.middleware.call_sync('sharing.smb.reg_getparm', section, parm)

        except Exception as e:
            raise CallError(f'Attempt to query smb4.conf parameter [{parm}] failed with error: {e}')
示例#21
0
class BaseController(WSGIController):

    AuthErr = {
        "success": False,
        "msg": 'Usted no esta autenticado'
    }
    successOK = {'success': True}
    lp = param.LoadParm()
    lp.load_default()

    def __init__(self):
        response.headers['Content-type'] = 'text/javascript; charset=utf-8'
        #response.write(self.__class__);

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        return WSGIController.__call__(self, environ, start_response)

    def index(self):
        if not self._check_session():
            return json.dumps(self.AuthErr)
        else:
            return json.dumps(self.successOK)

    def _check_session(self):
        if not 'username' in session:
            #response.write('False');
            return False
        return True

    def _connect(self):
        try:
            username = session['username']
            password = session['password']
            creds = credentials.Credentials()
            creds.set_username(username)
            creds.set_password(password)
            #creds.set_domain("SAMDOM")
            creds.set_domain("")
            creds.set_workstation("")
            self.conn = samba.Ldb("ldap://127.0.0.1",
                                  lp=self.lp,
                                  credentials=creds)
        except Exception, e:
            raise
        return True
示例#22
0
    def check_restored_smbconf(self):
        """Sanity-check important smb.conf values are restored correctly"""
        smbconf = os.path.join(self.restore_dir(), "etc", "smb.conf")
        bkp_lp = param.LoadParm(filename_for_non_global_lp=smbconf)
        self.assertEqual(bkp_lp.get('netbios name'), self.new_server)
        self.assertEqual(bkp_lp.get('workgroup'), self.restore_domain)
        self.assertEqual(bkp_lp.get('realm'), self.restore_realm.upper())

        # we restore with a fixed directory structure, so we can sanity-check
        # that the core filepaths settings are what we expect them to be
        private_dir = os.path.join(self.restore_dir(), "private")
        self.assertEqual(bkp_lp.get('private dir'), private_dir)
        state_dir = os.path.join(self.restore_dir(), "state")
        self.assertEqual(bkp_lp.get('state directory'), state_dir)
        return bkp_lp
示例#23
0
 def authenticate(self, usuario, password):
     # Connect to samba and attempt to authenticate this user
     print("SambaServer.authenticate: authenticating with %s and %s" %
           (usuario, password))
     lp = param.LoadParm()
     badge = Credentials()
     badge.guess(lp)
     badge.set_username(usuario)
     badge.set_password(password)
     # Intento la conexion.
     cx = SamDB(url='ldap://localhost', lp=lp, credentials=badge)
     print("cx returned: %s" % cx)
     # Get the domain from the SamDB and store it
     self.domain = cx.domain_dn()
     # Listo, la gracia es que si logre autenticarme con estos datos, y hay algun
     # resultado de mis acciones, voy a devolver algo.
     return cx
示例#24
0
    def setUp(self):
        super(SamDBTestCase, self).setUp()
        invocationid = str(uuid.uuid4())
        domaindn = "DC=COM,DC=EXAMPLE"
        self.domaindn = domaindn
        configdn = "CN=Configuration," + domaindn
        schemadn = "CN=Schema," + configdn
        domainguid = str(uuid.uuid4())
        policyguid = str(uuid.uuid4())
        creds = Credentials()
        creds.set_anonymous()
        domainsid = security.random_sid()
        hostguid = str(uuid.uuid4())
        path = os.path.join(self.tempdir, "samdb.ldb")
        session_info = system_session()

        hostname = "foo"
        domain = "EXAMPLE"
        dnsdomain = "example.com"
        serverrole = "domain controller"

        smbconf = os.path.join(self.tempdir, "smb.conf")
        make_smbconf(smbconf, self.setup_path, hostname, domain, dnsdomain,
                     serverrole, self.tempdir)

        self.lp = param.LoadParm()
        self.lp.load(smbconf)

        names = guess_names(lp=self.lp,
                            hostname=hostname,
                            domain=domain,
                            dnsdomain=dnsdomain,
                            serverrole=serverrole,
                            domaindn=self.domaindn,
                            configdn=configdn,
                            schemadn=schemadn)
        setup_templatesdb(os.path.join(self.tempdir, "templates.ldb"),
                          self.setup_path,
                          session_info=session_info,
                          lp=self.lp)
        self.samdb = setup_samdb(path, self.setup_path, session_info, creds,
                                 self.lp, names, lambda x: None, domainsid,
                                 domainguid, policyguid, False, "secret",
                                 "secret", "secret", invocationid, "secret",
                                 "domain controller")
示例#25
0
def connect_samdb_env(env_url, env_username, env_password, lp=None):
    """Connect to SamDB by getting URL and Credentials from environment

    :param env_url: Environment variable name to get lsb url from
    :param env_username: Username environment variable
    :param env_password: Password environment variable
    :return: sam_db_connection
    """
    samdb_url = env_get_var_value(env_url)
    creds = credentials.Credentials()
    if lp is None:
        # guess Credentials parameters here. Otherwise workstation
        # and domain fields are NULL and gencache code segfalts
        lp = param.LoadParm()
        creds.guess(lp)
    creds.set_username(env_get_var_value(env_username))
    creds.set_password(env_get_var_value(env_password))
    return connect_samdb(samdb_url, credentials=creds, lp=lp)
示例#26
0
文件: base.py 项目: zz38/smb4manager
class BaseController():

    AuthErr = {
        "success": False,
        "msg": 'Usted no esta autenticado'
    }
    successOK = {'success': True}
    lp = param.LoadParm()
    lp.load_default()

    def __init__(self):
        response.headers['Content-type'] = 'text/javascript; charset=utf-8'
        #response.write(self.__class__);

    def index(self):
        if not self._check_session():
            return json.dumps(self.AuthErr)
        else:
            return json.dumps(self.successOK)

    def _check_session(self):
        if not 'username' in session:
            #response.write('False');
            return False
        return True

    def _connect(self):
        try:
            username = session['username']
            password = session['password']
            creds = credentials.Credentials()
            creds.set_username(username)
            creds.set_password(password)
            #creds.set_domain("SAMDOM")
            creds.set_domain("")
            creds.set_workstation("")
            self.conn = samba.Ldb("ldap://127.0.0.1",
                                  lp=self.lp,
                                  credentials=creds)
        except Exception, e:
            raise
        return True
示例#27
0
    def create_smbconf(self, settings):
        """Creates a very basic smb.conf to pass to the restore tool"""

        # without the testenv config's settings, the NTACL backup_restore()
        # operation will fail (because we're not root). So first suck in all
        # testenv's settings, so we retain these in the new config. Note we
        # use a non-global LP so that these settings don't leak into other
        # places we use LoadParms
        testenv_conf = os.environ["SMB_CONF_PATH"]
        local_lp = param.LoadParm(filename_for_non_global_lp=testenv_conf)

        # add the new settings to the LP, then write the settings to file
        for key, val in settings.items():
            local_lp.set(key, val)

        new_smbconf = os.path.join(self.tempdir, "smb.conf")
        local_lp.dump(False, new_smbconf)

        self.addCleanup(os.remove, new_smbconf)
        return new_smbconf
示例#28
0
文件: share.py 项目: Schu23/GSoC-SWAT
    def share_name_exists(self, name):
        """ Checks if a Share exists in the Classic Backend. We reload the
        configuration file to make sure no modifications occured since we last
        loaded the file.
        
        Keyword arguments:
        name -- the share name to check
        
        Returns:
        True of False indicating if the Share exists or not
        
        """
        slp = param.LoadParm()
        slp.load(self._lp.configfile)

        for share in shares.SharesContainer(slp).keys():
            if share == name:
                return True

        log.warning("Share " + name + " doesn't exist")
        return False
示例#29
0
class BaseModel:
	lp = param.LoadParm()
	lp.load_default()
	creds=None
	LdapConn=None
	auth_success=False
	_isLastErrorAvailable=False
	LastErrorStr='';
	LastErrorNumber=0;
	RootDSE='' 
	DnsDomain='' 
	schemaNamingContext='' 
	Log = AppLog();
	
	def __init__(self,username,password):
		self.username=username;
		self.password=password;
		if self._connect():
			self._GetBase();

	def _connect(self):
		try:
			
			self.creds = credentials.Credentials()
			self.creds.set_username(self.username)
			self.creds.set_password(self.password)
			#self.creds.set_domain("SAMDOM")
			self.creds.set_domain("")
			self.creds.set_workstation("")
			self.LdapConn = samba.Ldb("ldap://127.0.0.1",lp=self.lp,credentials=self.creds)
			self.samrpipe = samr.samr("ncalrpc:", self.lp, self.creds)
			self.connect_handle = self.samrpipe.Connect(None, security.SEC_FLAG_MAXIMUM_ALLOWED)			
		except ldb.LdbError, (num, msg):
			self.SetError(msg,num)
			return False;
		except Exception,e:
			self.SetError(e.message,0)
			return False;
示例#30
0
文件: share.py 项目: Schu23/GSoC-SWAT
    def __init__(self):
        """ Initialization. Load the controller's configuration, builds the
        breadcrumb trail based on that information and load the backend
        information
        
        There are a few operations that don't require this initialization e.g.
        save, apply, cancel; they always redirect somewhere. therefore, there
        is a list of allowed operations that is checked to see if it's ok to
        load the configuration
        
        """
        me = request.environ['pylons.routes_dict']['controller']
        action = request.environ['pylons.routes_dict']['action']

        log.debug("Supported Backends: " + str(self.__supported_backends))
        log.debug("Controller: " + me)
        log.debug("Action: " + action)

        if action in self.__allowed:
            c.config = ControllerConfiguration(me, action)

            c.breadcrumb = BreadcrumbTrail(c.config)
            c.breadcrumb.build()

        c.samba_lp = param.LoadParm()
        c.samba_lp.load_default()

        log.debug("Configured backend is: " + c.samba_lp.get("share backend") +
                  " so the Class Name will be " +
                  c.samba_lp.get("share backend").title())

        if c.samba_lp.get("share backend") in self.__supported_backends:
            self.__backend = "ShareBackend" + c.samba_lp.get(
                "share backend").title()
        else:
            log.error("Unsupported Backend (" +
                      c.samba_lp.get("share backend") + ")")