Example #1
0
    def copySessionStart(self):
        profile_tmp_dir = os.path.join(Profile.TEMPORARY_PROFILE_PATH,
                                       self.session.user.name)
        if os.path.exists(profile_tmp_dir):
            System.rchown(profile_tmp_dir, self.session.user.name)

        if self.homeDir is None or not os.path.isdir(self.homeDir):
            return

        d = os.path.join(self.profile_mount_point, "conf.Linux")
        if not System.mount_point_exist(d):
            return

        if self.profile['profile_mode'] == 'advanced':
            return

        # Copy conf files
        d = self.transformToLocaleEncoding(d)
        cmd = self.getRsyncMethod(d, self.homeDir,
                                  Config.profile_filters_filename, True)
        Logger.debug("rsync cmd '%s'" % (cmd))

        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.error("Unable to copy conf from profile")
            Logger.debug(
                "Unable to copy conf from profile, cmd '%s' return %d: %s" %
                (cmd, p.returncode, p.stdout.read()))
Example #2
0
	def load_roles(self):
		for role in Config.roles:
			try:
				Role       = __import__("ovd.Role.%s.Role"  %(role), {}, {}, "Role")
				RoleDialog = __import__("ovd.Role.%s.Dialog"%(role), {}, {}, "Dialog")
				RoleConfig = __import__("ovd.Role.%s.Config"%(role), {}, {}, "Config")
			
			except ImportError:
				Logger.error("Unsupported role '%s'"%(role))
				import traceback
				Logger.debug(traceback.format_exc())
				return False
			
			if not RoleConfig.Config.init(Config.get_role_dict(role)):
				Logger.error("Unable to init configuration for role '%s'"%(role))
				return False
			
			RoleConfig.Config.general = Config
			
			role_instance = Role.Role(self)
			dialog_instance = RoleDialog.Dialog(role_instance)
			
			self.communication.dialogInterfaces.append(dialog_instance)
			self.role_dialogs.append((role_instance, dialog_instance))
		
		return True
Example #3
0
    def mount_cifs(self, share, uri, dest):
        mount_env = {}
        if share.has_key("login") and share.has_key("password"):
            cmd = "mount -t cifs -o 'uid=%s,gid=0,%s,iocharset=utf8' //%s%s %s" % (
                self.session.user.name,
                self.DEFAULT_PERMISSION,
                uri.netloc,
                uri.path,
                dest,
            )
            mount_env["USER"] = share["login"]
            mount_env["PASSWD"] = share["password"]
        else:
            cmd = "mount -t cifs -o 'guest,uid=%s,gid=0,%s,iocharset=utf8' //%s%s %s" % (
                self.session.user.name,
                self.DEFAULT_PERMISSION,
                uri.netloc,
                uri.path,
                dest,
            )

        cmd = self.transformToLocaleEncoding(cmd)
        Logger.debug("Profile, share mount command: '%s'" % (cmd))
        p = System.execute(cmd, env=mount_env)
        if p.returncode != 0:
            Logger.debug("CIFS mount failed (status: %d) => %s" % (p.returncode, p.stdout.read()))
            return False

        return True
Example #4
0
	def req_user_logout(self, request):
		try:
			document = minidom.parseString(request["data"])
			rootNode = document.documentElement
			
			if rootNode.nodeName != "user":
				raise Exception("invalid root node")
			
			if not rootNode.hasAttribute("login"):
				raise Exception("invalid root node")
			
			login = rootNode.getAttribute("login")
			
		except:
			Logger.warn("Invalid xml input !!")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		
		try:
			ret = Platform.TS.getSessionID(login)
		except Exception,err:
			Logger.error("RDP server dialog failed ... ")
			Logger.debug("Dialog::req_user_logout: %s"%(str(err)))
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "internalerror")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
Example #5
0
	def put_headers(self):
		headers, separator, body = self.communicator._buffer.partition("\r\n\r\n")

		if separator is '':
			# No or incomplete header chunk
			return None

		self.headers = headers + "\r\n"
		first_line = self.headers.split('\r\n', 1)[0]

		# Get requested service
		res = HttpMessage.http_req_ptn.search(first_line)
		if res is not None:
			self.path = res.group("url")
			self.service = Service.get(self.path)
		
		# Get Transfert encoding
		TE = self.get_header('Transfer-Encoding')
		if TE is not None and TE in 'chunked':
			self.TE = HttpMessage.CHUNKED
		else:
			self.TE = HttpMessage.DEFLATE
			len_body = self.get_header('Content-Length')
			if len_body is not None:
				self.len_body = int(len_body)

		if self.path is not '':
			Logger.debug("Gateway:: HTTP request: " + self.path)

		self.communicator._buffer = body
		return body;
Example #6
0
    def copySessionStart(self):
        profile_tmp_dir = os.path.join(Profile.TEMPORARY_PROFILE_PATH, self.session.user.name)
        if os.path.exists(profile_tmp_dir):
            System.rchown(profile_tmp_dir, self.session.user.name)

        if self.homeDir is None or not os.path.isdir(self.homeDir):
            return

        d = os.path.join(self.profile_mount_point, "conf.Linux")
        if not System.mount_point_exist(d):
            return

        if self.profile["profile_mode"] == "advanced":
            return

            # Copy conf files
        d = self.transformToLocaleEncoding(d)
        cmd = self.getRsyncMethod(d, self.homeDir, Config.profile_filters_filename, True)
        Logger.debug("rsync cmd '%s'" % (cmd))

        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.error("Unable to copy conf from profile")
            Logger.debug(
                "Unable to copy conf from profile, cmd '%s' return %d: %s" % (cmd, p.returncode, p.stdout.read())
            )
Example #7
0
    def put_headers(self):
        headers, separator, body = self.communicator._buffer.partition(
            "\r\n\r\n")

        if separator is '':
            # No or incomplete header chunk
            return None

        self.headers = headers + "\r\n"
        first_line = self.headers.split('\r\n', 1)[0]

        # Get requested service
        res = HttpMessage.http_req_ptn.search(first_line)
        if res is not None:
            self.path = res.group("url")
            self.service = Service.get(self.path)

        # Get Transfert encoding
        TE = self.get_header('Transfer-Encoding')
        if TE is not None and TE in 'chunked':
            self.TE = HttpMessage.CHUNKED
        else:
            self.TE = HttpMessage.DEFLATE
            len_body = self.get_header('Content-Length')
            if len_body is not None:
                self.len_body = int(len_body)

        if self.path is not '':
            Logger.debug("Gateway:: HTTP request: " + self.path)

        self.communicator._buffer = body
        return body
Example #8
0
    def process(self, request):
        path = request["path"]

        if request["method"] == "GET":
            Logger.debug("[WebApps] do_GET " + path)

            if path == "/sync":
                Logger.info("[WebApps] Starting config synchronization")
                setup_apps(reset=True)
                return self.req_answerText('OK')

            elif path.startswith("/session/status/"):
                buf = path[len("/session/status/"):]
                return self.req_session_status(buf)

            elif path.startswith("/session/destroy/"):
                buf = path[len("/session/destroy/"):]
                return self.req_session_destroy(buf)

        elif request["method"] == "POST":
            Logger.debug("[WebApps] do_POST " + path)
            if path == "/session/create":
                return self.req_session_create(request)

        Logger.info("WebApps role Dialog::process(%s)" % (str(request)))
        return None
Example #9
0
	def send_packet(self, path, document = None):
		if self.url is None:
			self.perform_dns_request()
		
		url = "%s%s"%(self.url, path)
		Logger.debug("SMRequest::send_packet url %s"%(url))
		
		req = urllib2.Request(url)
		req.add_header("Host", "%s:%s"%(self.host, self.port))
		
		if document is not None:
			rootNode = document.documentElement
			rootNode.setAttribute("name", str(self.name))
			req.add_header("Content-type", "text/xml; charset=UTF-8")
			req.add_data(document.toxml("UTF-8"))
		
		try:
			stream = urllib2.urlopen(req)
		except IOError:
			Logger.exception("SMRequest::send_packet path: "+path)
			return False
		except httplib.BadStatusLine:
			Logger.exception("SMRequest::send_packet path: "+path+" not receive HTTP response")
			return False
		
		return stream
Example #10
0
	def check_remaining_mount_points(self):
		try:
			user = pwd.getpwnam(System.local_encode(self.name))
		except KeyError:
			return False
		
		mount_points = MountPoint.get_list(user.pw_dir)
		if mount_points is None:
			return False
		
		success = True
		for d in mount_points:
			path = System.local_encode(d)
			Logger.warn("Remaining mount point '%s'"%(path))
			cmd = 'umount "%s"'%(path)
			
			p = System.execute(cmd)
			if p.returncode == 0:
				continue
			
			Logger.warn("Unable to unmount remaining mount point %s: force the unmount"%(path))
			Logger.debug('umount command "%s" return: %s'%(cmd,  p.stdout.read()))
			cmd = 'umount -l "%s"'%(path)
			p = System.execute(cmd)
			if p.returncode != 0:
				Logger.error("Unable to force the unmount remaining mount point %s"%(path))
				Logger.debug('umount command "%s" return: %s'%(cmd,  p.stdout.read()))
			
			success = False
		
		if success == False:
			Logger.error("Unable to unmount remaining mount point, home dir %s won't be purged"%(user.pw_dir))
		
		return success
Example #11
0
	def disable_password(self):
		lock = FileLock("/tmp/user.lock")
		
		cmd = 'passwd -r files -d "%s"'%(self.name)
		retry = 5
		while retry !=0:
			if retry < 0:
				Logger.error("ERROR: unable to disable user")
				return False
			lock.acquire()
			p = self.exec_command(cmd)
			lock.release()
			if p.returncode == 0:
				break
			
			Logger.debug("Passwd of %s:retry %i"%(self.name, 6-retry))
			if p.returncode == 5: # an other process is creating a user
				Logger.debug("An other process is creating a user")
				retry -=1
				time.sleep(0.2)
				continue
			if p.returncode != 0:
				Logger.error("passwd return %d (%s)"%(p.returncode, p.stdout.read()))
				return False
		return True
Example #12
0
	def purgeGroup(self):
		users = System.groupMember(Config.group)
		if users is None:
			return False
		
		ret = True
		for user in users:
			if user == Config.dav_user:
				continue
			
			Logger.debug("FileServer:: deleting user '%s'"%(user))
			
			u = User(user)
			u.clean()
			if u.existSomeWhere():
				Logger.error("FS: unable to del user %s"%(user))
				ret =  False
		
		htgroup = HTGroup(Config.dav_group_file)
		htgroup.purge()
		
		try:
			groups = [g.gr_name for g in grp.getgrall() if g.gr_name.startswith("ovd_share_")]
			for g in groups:
				System.groupDelete(g)
                except Exception:
                        Logger.exception("Failed to purge groups")
           		ret = False
		
		return ret
Example #13
0
	def req_share_delete(self, request):
		Logger.debug("FS:dialog::delete_share")
		try:
			document = minidom.parseString(request["data"])
			roodNode = document.documentElement
			if roodNode.nodeName != "share":
				raise Exception("invalid root node")
			
			share_id = roodNode.getAttribute("id")
			if len(share_id)==0 or "/" in share_id:
				raise Exception("invalid root node")
		
		except Exception:
			Logger.exception("Invalid xml input")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		if not self.role_instance.shares.has_key(share_id):
			Logger.debug("Unknown share '%s'"%(share_id))
			return self.share2xml(Share(share_id, Config.backendSpool, Config.spool))
		
		share = self.role_instance.shares[share_id]
		share.delete()
		del(self.role_instance.shares[share_id])
		
		return self.share2xml(share)
	def getIcon(self, filename):
		Logger.debug("ApplicationsDetection::getIcon %s"%(filename))
		
		try:
			entry = xdg.DesktopEntry.DesktopEntry(filename)
		except xdg.Exceptions.Error as detail:
			Logger.warn("ApplicationsDetection::getIcon %s" % detail)
			return None
		
		iconName = entry.getIcon()
		if entry.getIcon() == u'':
			# icon field is not required for type=Application
			return None
		
		iconPath = xdg.IconTheme.getIconPath(iconName, size = 32, theme=Config.linux_icon_theme, extensions = ["png", "xpm"])
		if iconPath == None:
			return None
		
		bufFile = tempfile.mktemp(".png")		
		cmd = 'convert -resize 32x32 "%s" "%s"'%(iconPath, bufFile)
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.debug("getIcon cmd '%s' returned (%d): %s"%(cmd, p.returncode, p.stdout.read()))
			Logger.error("getIcon: imagemagick error")
			if os.path.exists(bufFile):
				os.remove(bufFile)
			
			return None
		
		try:
			f = file(bufFile, "r")
		except IOError, err:
			Logger.error("ApplicationsDetection::getIcon finale icon file '%s' does not exists"%(bufFile))
			return None
Example #15
0
    def process(self, request):
        path = request["path"]

        if request["method"] == "GET":
            Logger.debug("do_GET " + path)

            if path == "/configuration":
                return self.req_server_conf(request)

            elif path == "/monitoring":
                return self.req_server_monitoring(request)

            elif path == "/status":
                return self.req_server_status(request)

            elif path.startswith("/logs"):
                since = 0
                extra = path[len("/logs"):]
                if extra.startswith("/since/"):
                    since_str = extra[len("/since/"):]
                    if since_str.isdigit():
                        since = int(since_str)
                elif len(extra) > 0:
                    return None

                return self.req_server_logs(request, since)

            return None

        elif request["method"] == "POST":
            return None

        return None
Example #16
0
    def mount(self):
        buf = self.getFreeLetter()
        if buf is None:
            Logger.warn("No drive letter available: unable to init profile")
            return

        self.mountPoint = "%s:" % (buf)

        try:
            win32wnet.WNetAddConnection2(
                win32netcon.RESOURCETYPE_DISK, self.mountPoint,
                r"\\%s\%s" % (self.profile["server"], self.profile["dir"]),
                None, self.profile["login"], self.profile["password"])

        except Exception, err:
            Logger.error("Unable to mount drive")
            Logger.debug("WNetAddConnection2 return %s" % (err))
            Logger.debug(
                "Unable to mount drive, '%s', try the net use command equivalent: '%s'"
                %
                (str(err), "net use %s \\\\%s\\%s %s /user:%s" %
                 (self.mountPoint, self.profile["server"], self.profile["dir"],
                  self.profile["password"], self.profile["login"])))

            self.mountPoint = None
            return False
Example #17
0
	def main(self):
		self.synchronizer.restore()
		Logger._instance.setQueue(self.logging_queue, False)
		
		System.prepareForSessionActions()
		
		# Prevent the process to be stop by a keyboard interruption
		signal.signal(signal.SIGINT, signal.SIG_IGN)
		signal.signal(signal.SIGTERM, signal.SIG_IGN)
		
		Logger.debug("Starting SessionManager process")
		while True:
			self.current_session_id.value = ""
			try:
				(request, obj) = self.queue2.get_nowait()
			except Queue.Empty:
				try:
					(request, obj) = self.queue.get(True, 4)
				except Queue.Empty, e:
					continue
				except IOError, e:
					if e.errno == 4:
						break
					else:
						raise e
Example #18
0
	def create_session(self, session):
		Logger.info("SessionManagement::create %s for user %s"%(session.id, session.user.name))
		
		
		if System.userExist(session.user.name):
			Logger.error("unable to create session: user %s already exists"%(session.user.name))
			session.end_status = Session.SESSION_END_STATUS_ERROR
			self.aps_instance.session_switch_status(session, Session.SESSION_STATUS_ERROR)
			return self.destroy_session(session)
					
		rr = session.user.create()
		
		if rr is False:
			Logger.error("unable to create session for user %s"%(session.user.name))
			session.end_status = Session.SESSION_END_STATUS_ERROR
			self.aps_instance.session_switch_status(session, Session.SESSION_STATUS_ERROR)
			return self.destroy_session(session)
			
		
		session.user.created = True
					
		try:
			rr = session.install_client()
		except Exception,err:
			Logger.debug("Unable to initialize session %s: %s"%(session.id, str(err)))
			rr = False
Example #19
0
    def handle_read(self):
        # Read data in buffer
        SecureServerCommunicator.handle_read(self)

        # Fetch the Http request from parent communicator
        if (self.http_communicator is None) and (len(
                self.communicator.http_history) > 0):
            self.http_communicator = self.communicator.http_history.pop(0)

            if self.http_communicator.path in Config.force_buffering:
                Logger.debug("Force buffering : " +
                             self.http_communicator.path)
                self.http.force_full_buffering = True

        if not self.http.is_ready():
            # Parse it until ready
            if self.make_http_message():
                # Now it is ready
                self._buffer = self.process()  # Stream it
                self.http_communicator = None
        else:
            # Data is streamed "on-the-fly"
            self._buffer = self._buffer  # Stream it

        if self.http.is_complete():
            self.http = HttpMessage(self)
Example #20
0
    def logoff_user(self, user):
        Logger.info("SessionManagement::logoff_user %s" % (user.name))

        if user.infos.has_key("tsid"):
            sessid = user.infos["tsid"]

            try:
                status = RolePlatform.TS.getState(sessid)
            except Exception, err:
                Logger.error("RDP server dialog failed ... ")
                Logger.debug("SessionManagement::logoff_user: %s" % (str(err)))
                return

            if status in [
                    RolePlatform.TS.STATUS_LOGGED,
                    RolePlatform.TS.STATUS_DISCONNECTED
            ]:
                Logger.info("must log off ts session %s user %s" %
                            (sessid, user.name))

                try:
                    RolePlatform.TS.logoff(sessid)
                except Exception, err:
                    Logger.error("RDP server dialog failed ... ")
                    Logger.debug("SessionManagement::logoff_user: %s" %
                                 (str(err)))
                    return

                del (user.infos["tsid"])
Example #21
0
    def run(self):
        self.synchronizer.restore()
        Logger._instance.setQueue(self.logging_queue, False)
        loop = True

        Platform.System.prepareForSessionActions()

        # Prevent the process to be stop by a keyboard interruption
        def quit(machin, truc):
            global loop
            loop = False

        signal.signal(signal.SIGINT, signal.SIG_IGN)
        signal.signal(signal.SIGTERM, quit)

        Logger.debug("Starting SessionManager process")
        while loop:
            try:
                (request, obj) = self.queue2.get_nowait()
            except Queue.Empty:
                try:
                    (request, obj) = self.queue.get(True, 4)
                except Queue.Empty, e:
                    continue
                except IOError, e:
                    if e.errno == 4:
                        break
                    else:
                        raise e
 def setInstance(cls, instance):
     if cls._instance is None:
         Logger.debug('[WebApps] ApplicationsRepository instance set')
         cls._instance = instance
     else:
         Logger.debug(
             '[WebApps] ApplicationsRepository instance already set')
Example #23
0
	def process(self, request):
		path = request["path"]
		
		if request["method"] == "GET":
			Logger.debug("do_GET "+path)
			
			if path == "/configuration":
				return self.req_server_conf(request)
			
			elif path == "/monitoring":
				return self.req_server_monitoring(request)
			
			elif path == "/status":
				return self.req_server_status(request)
			
			elif path.startswith("/logs"):
				since = 0
				extra = path[len("/logs"):]
				if extra.startswith("/since/"):
					since_str = extra[len("/since/"):]
					if since_str.isdigit():
						since = int(since_str)
				elif len(extra) > 0:
					return None  
				
				return self.req_server_logs(request, since)
			
			return None
		
		elif request["method"] == "POST":
			return None
		
		return None
Example #24
0
	def check_ssl_certs(self):
		"""
		Validate SSL Certificates
		"""
		target_host = self.config['target'].netloc
		try:
			cert = ssl.get_server_certificate((target_host, 443))
			x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
		except:
			Logger.exception('Error when loading certificate')
			return False
		# Check if certificate has expired
		if x509.has_expired():
			Logger.debug('Certificate has expired')
			return False
		# Check if certificate is self-signed
		if x509.get_issuer() == x509.get_subject():
			Logger.debug('Certificate is self-signed')
			return False
		# Check domain
		try:
			cn = [comp[1] for comp in x509.get_subject().get_components() if comp[0] == 'CN'][0]
		except Exception:
			Logger.debug('CN not found')
			return False
		if cn.startswith('*'):
			if not re.match(r'(\w+\.)*' + cn.lstrip('*.'), target_host):
				Logger.debug('CN of the certificate does not match target host')
				return False
		elif not target_host == cn:
			Logger.debug('CN of the certificate does not match target host')
			return False
		return True
Example #25
0
	def del_user(self, user):
		if user not in self.ro_users and user not in self.rw_users:
			return True
		
		ret = True
		if user in self.ro_users:
			cmd = "deluser %s %s_ro"%(user, self.group)
		else:
			cmd = "deluser %s %s_rw"%(user, self.group)
		
		p = System.execute(cmd)
		if p.returncode is not 0:
			ret = False
			Logger.error("FS: unable to del user in group")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
		
		htgroup = HTGroup(Config.dav_group_file)
		
		if user in self.ro_users:
			self.ro_users.remove(user)
			htgroup.delete(user, self.group+"_ro")
		if user in self.rw_users:
			self.rw_users.remove(user)
			htgroup.delete(user, self.group+"_rw")
		
		if (len(self.ro_users) + len(self.rw_users)) == 0:
			return self.disable()
		
		return True
Example #26
0
    def load_roles(self):
        for role in Config.roles:
            try:
                Role = __import__("ovd.Role.%s.Role" % (role), {}, {}, "Role")
                RoleDialog = __import__("ovd.Role.%s.Dialog" % (role), {}, {}, "Dialog")
                RoleConfig = __import__("ovd.Role.%s.Config" % (role), {}, {}, "Config")

            except ImportError:
                Logger.error("Unsupported role '%s'" % (role))
                import traceback

                Logger.debug(traceback.format_exc())
                return False

            if not RoleConfig.Config.init(Config.get_role_dict(role)):
                Logger.error("Unable to init configuration for role '%s'" % (role))
                return False

            RoleConfig.Config.general = Config

            role_instance = Role.Role(self)
            dialog_instance = RoleDialog.Dialog(role_instance)

            self.communication.dialogInterfaces.append(dialog_instance)
            self.role_dialogs.append((role_instance, dialog_instance))

        return True
Example #27
0
    def set_password(self):
        lock = FileLock("/tmp/user.lock")

        cmd = 'passwd -r files "%s"' % (self.name)
        password = "******" % (self.infos["password"])
        retry = 5
        while retry != 0:
            if retry < 0:
                Logger.error("ERROR: unable to add a new user")
                return False

            lock.acquire()
            p = self.exec_command(cmd, False)
            p.stdin.write(password)
            p.stdin.write(password)
            p.wait()
            lock.release()
            if p.returncode == 0:
                break

            Logger.debug("Passwd of %s:retry %i" % (self.name, 6 - retry))
            if p.returncode == 5:  # an other process is creating a user
                Logger.debug("An other process is creating a user")
                retry -= 1
                time.sleep(0.2)
                continue
            if p.returncode != 0:
                Logger.error("chpasswd return %d (%s)" %
                             (p.returncode, p.stdout.read()))
                return False
        return True
Example #28
0
    def enable(self, mode):
        for i in ['ro', 'rw']:
            cmd = "groupadd  %s_%s" % (self.group, i)
            p = System.execute(cmd)
            if p.returncode is not 0:
                Logger.error("FS: unable to create group")
                Logger.debug(
                    "FS: command '%s' return %d: %s" %
                    (cmd, p.returncode, p.stdout.read().decode("UTF-8")))
                return False

        cmd = 'net usershare add %s "%s" %s %s_ro:r,%s_rw:f guest_ok=n' % (
            self.name, self.frontDirectory, self.name, self.group, self.group)
        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.error("FS: unable to add share")
            Logger.debug("FS: command '%s' return %d: %s" %
                         (cmd, p.returncode, p.stdout.read().decode("UTF-8")))
            return False

        self.do_right_normalization()

        self.htaccess.addGroup(self.group)
        self.htaccess.save()

        self.active = True
        return True
Example #29
0
	def set_password(self):
		lock = FileLock("/tmp/user.lock")
		
		cmd = 'passwd -r files "%s"'%(self.name)
		password = "******"%(self.infos["password"])
		retry = 5
		while retry !=0:
			if retry < 0:
				Logger.error("ERROR: unable to add a new user")
				return False
			
			lock.acquire()
			p = self.exec_command(cmd, False)
			p.stdin.write(password)
			p.stdin.write(password)
			p.wait()
			lock.release()
			if p.returncode == 0:
				break
			
			Logger.debug("Passwd of %s:retry %i"%(self.name, 6-retry))
			if p.returncode == 5: # an other process is creating a user
				Logger.debug("An other process is creating a user")
				retry -=1
				time.sleep(0.2)
				continue
			if p.returncode != 0:
				Logger.error("chpasswd return %d (%s)"%(p.returncode, p.stdout.read()))
				return False
		return True
Example #30
0
    def del_user(self, user):
        if user not in self.ro_users and user not in self.rw_users:
            return True

        ret = True
        if user in self.ro_users:
            cmd = "deluser %s %s_ro" % (user, self.group)
        else:
            cmd = "deluser %s %s_rw" % (user, self.group)

        p = System.execute(cmd)
        if p.returncode is not 0:
            ret = False
            Logger.error("FS: unable to del user in group")
            Logger.debug("FS: command '%s' return %d: %s" %
                         (cmd, p.returncode, p.stdout.read().decode("UTF-8")))

        htgroup = HTGroup(Config.dav_group_file)

        if user in self.ro_users:
            self.ro_users.remove(user)
            htgroup.delete(user, self.group + "_ro")
        if user in self.rw_users:
            self.rw_users.remove(user)
            htgroup.delete(user, self.group + "_rw")

        if (len(self.ro_users) + len(self.rw_users)) == 0:
            return self.disable()

        return True
Example #31
0
    def disable_password(self):
        lock = FileLock("/tmp/user.lock")

        cmd = 'passwd -r files -d "%s"' % (self.name)
        retry = 5
        while retry != 0:
            if retry < 0:
                Logger.error("ERROR: unable to disable user")
                return False
            lock.acquire()
            p = self.exec_command(cmd)
            lock.release()
            if p.returncode == 0:
                break

            Logger.debug("Passwd of %s:retry %i" % (self.name, 6 - retry))
            if p.returncode == 5:  # an other process is creating a user
                Logger.debug("An other process is creating a user")
                retry -= 1
                time.sleep(0.2)
                continue
            if p.returncode != 0:
                Logger.error("passwd return %d (%s)" %
                             (p.returncode, p.stdout.read()))
                return False
        return True
Example #32
0
	def run(self):
		self.synchronizer.restore()
		Logger._instance.setQueue(self.logging_queue, False)
		global loop
		loop = True

		Platform.System.prepareForSessionActions()
		
		# Prevent the process to be stop by a keyboard interruption
		def quit(machin, truc):
			global loop
			loop = False
		signal.signal(signal.SIGINT, signal.SIG_IGN)
		signal.signal(signal.SIGTERM, quit)
		
		Logger.debug("Starting SessionManager process")
		while loop:
			try:
				(request, obj) = self.queue2.get_nowait()
			except Queue.Empty:
				try:
					(request, obj) = self.queue.get(True, 4)
				except Queue.Empty, e:
					continue
				except IOError, e:
					if e.errno == 4:
						break
					else:
						raise e
Example #33
0
    def main(self):
        self.synchronizer.restore()
        Logger._instance.setQueue(self.logging_queue, False)

        System.prepareForSessionActions()

        # Prevent the process to be stop by a keyboard interruption
        signal.signal(signal.SIGINT, signal.SIG_IGN)
        signal.signal(signal.SIGTERM, signal.SIG_IGN)

        Logger.debug("Starting SessionManager process")
        while True:
            self.current_session_id.value = ""
            try:
                (request, obj) = self.queue2.get_nowait()
            except Queue.Empty:
                try:
                    (request, obj) = self.queue.get(True, 4)
                except Queue.Empty, e:
                    continue
                except IOError, e:
                    if e.errno == 4:
                        break
                    else:
                        raise e
Example #34
0
    def process(self, request):
        path = request["path"]

        if request["method"] == "GET":

            Logger.debug("do_GET " + path)

            if path == "/status":
                return self.req_status()

        elif request["method"] == "POST":

            Logger.debug("do_POST " + path)

            if path == "/vm/destroy":
                return self.req_delete(request)

            if path == "/vm/create":
                return self.req_create(request)

            if path == "/vm/manage":
                return self.req_manage(request)

            if path == "/vm/name":
                return self.req_name(request)

            if path == "/vm/configure":
                return self.req_configure(request)

        return None
Example #35
0
	def process(self, request):
		path = request["path"]
		
		if request["method"] == "GET":
			
			Logger.debug("do_GET "+path)
			
			if path == "/status" :
				return self.req_status()
		
		
		elif request["method"] == "POST":
			
			Logger.debug("do_POST "+path)
			
			if path == "/vm/destroy":
				return self.req_delete(request)
	
			if path == "/vm/create":
				return self.req_create(request)
	
			if path == "/vm/manage":
				return self.req_manage(request)
				
			if path == "/vm/name":
				return self.req_name(request)
				
			if path == "/vm/configure":
				return self.req_configure(request)
		
		return None
Example #36
0
	def run(self):
		self.updateApplications()
		self.has_run = True
		
		Logger._instance.lock.acquire()
		Logger._instance.close()
		for thread in self.threads:
			thread.start()
		Logger._instance.lock.release()
		
		t0_update_app = time.time()
		
		self.status = Role.STATUS_RUNNING
		
		while self.thread.thread_continue():
			while True:
				try:
					session = self.sessions_sync.get_nowait()
				except Queue.Empty, e:
					break
				except (EOFError, socket.error):
					Logger.debug("Role stopping")
					return
				
				if not self.sessions.has_key(session.id):
					Logger.warn("Session %s do not exist, session information are ignored"%(session.id))
					continue
				
				if session.status != self.sessions[session.id].status:
					self.manager.session_switch_status(session, session.status)
				
				if session.status == RolePlatform.Session.SESSION_STATUS_DESTROYED:
					del(self.sessions[session.id])
				else:
					self.sessions[session.id] = session
Example #37
0
    def process(self, request):
        path = request["path"]

        if request["method"] == "GET":
            Logger.debug("[WebApps] do_GET " + path)

            if path == "/sync":
                Logger.info("[WebApps] Starting config synchronization")
                setup_apps(reset=True)
                return self.req_answerText("OK")

            elif path.startswith("/session/status/"):
                buf = path[len("/session/status/") :]
                return self.req_session_status(buf)

            elif path.startswith("/session/destroy/"):
                buf = path[len("/session/destroy/") :]
                return self.req_session_destroy(buf)

        elif request["method"] == "POST":
            Logger.debug("[WebApps] do_POST " + path)
            if path == "/session/create":
                return self.req_session_create(request)

        Logger.info("WebApps role Dialog::process(%s)" % (str(request)))
        return None
Example #38
0
    def purgeGroup(self):
        users = System.groupMember(Config.group)
        if users is None:
            return False

        ret = True
        for user in users:
            if user == Config.dav_user:
                continue

            Logger.debug("FileServer:: deleting user '%s'" % (user))

            u = User(user)
            u.clean()
            if u.existSomeWhere():
                Logger.error("FS: unable to del user %s" % (user))
                ret = False

        htgroup = HTGroup(Config.dav_group_file)
        htgroup.purge()

        try:
            groups = [
                g.gr_name for g in grp.getgrall()
                if g.gr_name.startswith("ovd_share_")
            ]
            for g in groups:
                System.groupDelete(g)
        except Exception:
            Logger.exception("Failed to purge groups")
            ret = False

        return ret
Example #39
0
	def post_process(self, context):
		"""
		Check if server responsed 302 to login page,
		if yes - login and send request again.

		When server responsed 200, parse result content with
		content_regexp. If match, login and send request again.
		"""
		Logger.debug("StaticRequestFilter post_process")
		session = context.session
		
		if re.search("^HTTP/[\d\.]* 200", context.result[0]):
			if session.has_key('ulteo_autologin') and type(session['ulteo_autologin']) in (str, unicode):
				context.body = session['ulteo_autologin']
			
			elif self.options.has_key('content_regexp') and isinstance(context.body, str) and re.search(self.options['content_regexp'], context.body, re.DOTALL) != None:
				session['ulteo_autologin'] = True
				send_buffer = """
HTTP/1.1 302 Moved
Location: {0}
Content-Type: text/html
Content-Length: 174

<html>
<head>
<title>Moved</title>
</head>
<body>
<h1>Moved</h1>
</body>
</html>
				""".format(self.rewrite_url(context.requested_path)).strip()
				sent = context.communicator.send(send_buffer)
		
		
		if context.result[0].startswith('HTTP/1.1 302'):
			for line in context.result:
				if line.startswith('Location: '):
					host = line[10:]
					if hasattr(self.options, 'regexp') and re.search(self.options['regexp'], host):
						session['ulteo_autologin'] = False
						
						Logger.debug("Found login location in redirect, redirecting to: " + context.requested_path)
						send_buffer = """
HTTP/1.1 302 Moved
Location: {0}
Content-Type: text/html
Content-Length: 174

<html>
<head>
<title>Moved</title>
</head>
<body>
<h1>Moved</h1>
</body>
</html>
						""".format(context.requested_path).strip()
						context.communicator.send(send_buffer)
Example #40
0
	def install_client(self):
		name = System.local_encode(self.user.name)
		
		d = os.path.join(self.SPOOL_USER, self.user.name)
		self.init_user_session_dir(d)
		self.install_desktop_shortcuts()
		
		os.chown(self.instanceDirectory, pwd.getpwnam(name)[2], -1)
		os.chown(self.user_session_dir, pwd.getpwnam(name)[2], -1)
		
		xdg_dir = os.path.join(d, "xdg")
		xdg_app_d = os.path.join(xdg_dir, "applications")
		if not os.path.isdir(xdg_app_d):
			os.makedirs(xdg_app_d)
		
		for p in ["icons", "pixmaps", "mime", "themes"]:
			src_dir = os.path.join("/usr/share/", p)
			dst_dir =  os.path.join(xdg_dir, p)
			
			os.symlink(src_dir, dst_dir)
		
		
		os.system('update-desktop-database "%s"'%(System.local_encode(xdg_app_d)))
	
		if self.parameters.has_key("desktop_icons") and self.parameters["desktop_icons"] == "1":
			path = os.path.join(xdg_app_d, ".show_on_desktop")
			f = file(path, "w")
			f.close()
		
		
		env_file_lines = []
		# Set the language
		if self.parameters.has_key("locale"):
			env_file_lines.append("LANG=%s.UTF-8\n"%(self.parameters["locale"]))
			env_file_lines.append("LC_ALL=%s.UTF-8\n"%(self.parameters["locale"]))
			env_file_lines.append("LANGUAGE=%s.UTF-8\n"%(self.parameters["locale"]))
		
		if self.parameters.has_key("timezone"):
			tz_file = "/usr/share/zoneinfo/" + self.parameters["timezone"]
			if not os.path.exists(tz_file):
				Logger.warn("Unsupported timezone '%s'"%(self.parameters["timezone"]))
				Logger.debug("Unsupported timezone '%s'. File '%s' does not exists"%(self.parameters["timezone"], tz_file))
			else:
				env_file_lines.append("TZ=%s\n"%(tz_file))
		
		f = file(os.path.join(d, "env"), "w")
		f.writelines(env_file_lines)
		f.close()
		
		if self.profile is not None:
			self.profile.mount()
			
			shares_dir = os.path.join(d, "shares")
			if not os.path.isdir(shares_dir):
				os.makedirs(shares_dir)
			
			self.profile.register_shares(shares_dir)
		
		return True
Example #41
0
	def logoff(session_id):
		try:
			Logger.debug("perform_logoff: start logoff %d"%(session_id))
			ret = win32ts.WTSLogoffSession(None, session_id, True)
			Logger.debug("perform_logoff: finish logoff %d ret: %s"%(session_id, str(ret)))
		except Exception, e:
			Logger.warn("perform_logoff: exception %s"%(e))
			return False
Example #42
0
	def getExec(filename):
		Logger.debug("ApplicationsDetection::getExec %s"%(filename))
		cmd = LnkFile.getTarget(filename)
		if cmd is None:
			Logger.error("Unable to get command from shortcut '%s'"%(filename))
			return None
		
		return cmd
Example #43
0
 def run(self):
     self.has_run = True
     self.status = Role.STATUS_RUNNING
     self.wm.start()
     while 1:
         time.sleep(30)
         Logger.debug("FileServer run loop")
     self.status = Role.STATUS_STOP
Example #44
0
	def delete(self):
		cmd = "rm -rf %s"%(self.directory)
		s, o = commands.getstatusoutput(cmd)
		if s is not 0:
			Logger.error("FS: unable to del share")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, s, o.decode("UTF-8")))
		
		return s == 0
	def run(self):
		try:
			reactor.listenTCP(self.tcp_port, self.site)
		except BindError, exc:
			Logger.error("Unable to bind port %d, system is going to stop"%(self.tcp_port))
			Logger.debug("Unable to bind port %d: "%(self.tcp_port)+str(exc))
			self.status = AbstractCommunication.STATUS_ERROR
			return
Example #46
0
	def run(self):
		self.has_run = True
		self.status = Role.STATUS_RUNNING
		self.wm.start()
		while 1:
			time.sleep(30)
			Logger.debug("FileServer run loop")
		self.status = Role.STATUS_STOP
	def getExec(filename):
		Logger.debug("ApplicationsDetection::getExec %s"%(filename))
		cmd = LnkFile.getTarget(filename)
		if cmd is None:
			Logger.error("Unable to get command from shortcut '%s'"%(filename))
			return None
		
		return cmd
Example #48
0
	def create(self):
		lock = FileLock("/tmp/user.lock")
		
		# TODO get the default home in /etc/default/useradd
		default_home_dir = os.path.join(u"/home", self.name)
		home_dir = default_home_dir
		i = 0
		while os.path.exists(home_dir) and i < 100:
			home_dir = default_home_dir+"_%d"%(i)
			i+= 1

		if i > 0:
			Logger.warn("Unable to create home directory %s, the home is now %s"%(default_home_dir, home_dir))

		if os.path.exists(home_dir):
			Logger.error("Unable to find a valid home directory")
			return False
		
		cmd = u"useradd -m -d '%s' -k '%s'"%(home_dir, Config.linux_skel_directory)
		if self.infos.has_key("displayName"):
			cmd+= u""" --comment "%s,,," """%(self.infos["displayName"].replace('"', ""))
		
		groups = ["video", "audio", "pulse", "pulse-access", Config.linux_fuse_group]
		if self.infos.has_key("groups"):
			groups+= self.infos["groups"]
		cmd+= u" --groups %s"%(",".join(groups))
		
		cmd+= u" "+self.name
		
		retry = 5
		while retry !=0:
			if retry < 0:
				  Logger.error("ERROR: unable to add a new user")
			lock.acquire()
			p = System.execute(System.local_encode(cmd))
			lock.release()
			if p.returncode == 0:
				break
			
			Logger.debug("Add user :retry %i"%(6-retry))
			if p.returncode == 9: # user already exist
				Logger.error("User %s already exist"%(self.name))
				break;
			if p.returncode == 1: # an other process is creating a user
				Logger.error("An other process is creating a user")
				retry -=1
				time.sleep(0.2)
				continue
			if p.returncode != 0:
				Logger.error("UserAdd return %d (%s)"%(p.returncode, p.stdout.read()))
				return False
		
		
		if self.infos.has_key("password"):
			if not self.set_password():
				return False
		
		return self.post_create()
Example #49
0
	def get(self):
		applications = {}
		
		(_, encoding) = locale.getdefaultlocale()
		if encoding is None:
			encoding = "utf8"
		
		files = self.find_lnk()
		
		for filename in files:
			shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
			shortcut.QueryInterface( pythoncom.IID_IPersistFile ).Load(filename)
			
			name = os.path.basename(filename)[:-4]
			if self.isBan(name):
				continue
			
			try:
				local_id = hashlib.md5(filename.encode(encoding)).hexdigest()
			except UnicodeEncodeError, err:
				local_id = hashlib.md5(filename.encode('utf-8')).hexdigest()
			
			application = {}
			application["local_id"] = local_id
			application["name"] = name
			application["command"] = unicode(shortcut.GetPath(0)[0], encoding)
			application["filename"] = filename
			
			if len(shortcut.GetIconLocation()[0])>0:
				application["icon"]  = unicode(shortcut.GetIconLocation()[0], encoding)
			
			
			if self.msi is not None:
				buf = self.msi.getTargetFromShortcut(filename)
				if buf is not None:
					application["command"] = buf
			
			if not application["command"].lower().endswith(".exe") and ".exe " not in application["command"].lower():
				continue
			
			if win32process.IsWow64Process() and not os.path.exists(application["command"]):
				application["command"] = Util.clean_wow64_path(application["command"])
			
			if " " in application["command"]:
				application["command"] = '"%s"'%(application["command"])
			
			if len(shortcut.GetArguments())>0:
				application["command"]+= " "+unicode(shortcut.GetArguments(), encoding)
			
			try:
				if len(shortcut.GetDescription())>0:
					application["description"] = unicode(shortcut.GetDescription(), encoding)
			except pywintypes.com_error:
				Logger.debug("ApplicationsDetection::get unable to get description for %s"%(application["filename"]))
			
			application["mimetypes"] = self.mimetypes.get_mime_types_from_command(application["command"])
			
			applications[application["local_id"]] = application
	def get(self):
		applications = {}
		
		(_, encoding) = locale.getdefaultlocale()
		if encoding is None:
			encoding = "utf8"
		
		files = self.find_lnk()
		
		for filename in files:
			shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
			shortcut.QueryInterface( pythoncom.IID_IPersistFile ).Load(filename)
			
			name = os.path.basename(filename)[:-4]
			if self.isBan(name):
				continue
			
			try:
				local_id = hashlib.md5(filename.encode(encoding)).hexdigest()
			except UnicodeEncodeError, err:
				local_id = hashlib.md5(filename.encode('utf-8')).hexdigest()
			
			application = {}
			application["local_id"] = local_id
			application["name"] = name
			application["command"] = unicode(shortcut.GetPath(0)[0], encoding)
			application["filename"] = filename
			
			if len(shortcut.GetIconLocation()[0])>0:
				application["icon"]  = unicode(shortcut.GetIconLocation()[0], encoding)
			
			
			if self.msi is not None:
				buf = self.msi.getTargetFromShortcut(filename)
				if buf is not None:
					application["command"] = buf
			
			if not application["command"].lower().endswith(".exe") and ".exe " not in application["command"].lower():
				continue
			
			if win32process.IsWow64Process() and not os.path.exists(application["command"]):
				application["command"] = Util.clean_wow64_path(application["command"])
			
			if " " in application["command"]:
				application["command"] = '"%s"'%(application["command"])
			
			if len(shortcut.GetArguments())>0:
				application["command"]+= " "+unicode(shortcut.GetArguments(), encoding)
			
			try:
				if len(shortcut.GetDescription())>0:
					application["description"] = unicode(shortcut.GetDescription(), encoding)
			except pywintypes.com_error:
				Logger.debug("ApplicationsDetection::get unable to get description for %s"%(application["filename"]))
			
			application["mimetypes"] = self.mimetypes.get_mime_types_from_command(application["command"])
			
			applications[application["local_id"]] = application
Example #51
0
    def push_production(self):
        # Initialisation
        try:
            if not self.smRequestManager.initialize():
                raise Exception()
        except Exception, e:
            Logger.debug("smRequestManager initialize returned %s" % (str(e)))

            return False
Example #52
0
    def delete(self):
        cmd = "rm -rf %s" % (self.directory)
        s, o = commands.getstatusoutput(cmd)
        if s is not 0:
            Logger.error("FS: unable to del share")
            Logger.debug("FS: command '%s' return %d: %s" %
                         (cmd, s, o.decode("UTF-8")))

        return s == 0
Example #53
0
    def init(self):
        Logger.debug("ApplicationServer init")

        try:
            RolePlatform.TS.getList()
        except Exception, err:
            Logger.error("RDP server dialog failed ... exiting")
            Logger.debug("RDP server dialog: " + str(err))
            return
Example #54
0
    def send_server_name(self):
        url = "%s/server/name" % (self.url)
        Logger.debug('SMRequest::server_name url ' + url)

        req = urllib2.Request(url)
        try:
            f = urllib2.urlopen(req)
        except IOError, e:
            Logger.debug("SMRequest::server_status error" + str(e))
            return None
Example #55
0
    def delete(self):
        cmd = "rm -rf %s" % (self.directory)
        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.error("FS: unable to del share")
            Logger.debug("FS: command '%s' return %d: %s" %
                         (cmd, p.returncode, p.stdout.read().decode("UTF-8")))
            return False

        return True
Example #56
0
	def init_user_session_dir(self, user_session_dir):
		self.user_session_dir = user_session_dir
		if os.path.isdir(self.user_session_dir):
			Platform.System.DeleteDirectory(self.user_session_dir)
		
		try:
			os.makedirs(self.user_session_dir)
		except WindowsError, e:
			if e[0] == 183 : # The directory already exist
				Logger.debug("The directory %s already exist"%(self.user_session_dir))