def readable(self): if time.time() - self.lastPacketTime > Config.connection_timeout: Logger.error("ProtocolDetectDispatcher::connection timeout") self.handle_close() return False return True
def uninstall_client(self): if not self.succefully_initialized: return self.archive_shell_dump() if self.profile is not None and self.profile.hasProfile(): if not self.profile.mount(): Logger.warn( "Unable to mount profile at uninstall_client of session " + self.id) else: self.profile.copySessionStop() if not self.profile.umount(): Logger.error( "Unable to umount profile at uninstall_client of session " + self.id) try: shutil.rmtree(self.user_session_dir) except Exception: Logger.exception("Failed to remove spool directory '%s'" % self.user_session_dir) self.domain.onSessionEnd() return True
def uninstall_client(self): if not self.succefully_initialized: return self.archive_shell_dump() if self.profile is not None and self.profile.hasProfile(): if not self.profile.mount(): Logger.warn( "Unable to mount profile at uninstall_client of session " + self.id) else: self.profile.copySessionStop() desktop_path = os.path.join(self.profile.mountPoint, self.profile.DesktopDir) self.cleanupShortcut(desktop_path) for shortcut in self.installedShortcut: dstFile = os.path.join(self.profile.mountPoint, self.profile.DesktopDir, shortcut) if os.path.exists(dstFile): os.remove(dstFile) if not self.profile.umount(): Logger.error( "Unable to umount profile at uninstall_client of session " + self.id) self.domain.onSessionEnd() return True
def create(self): userData = {} userData['name'] = self.name if self.infos.has_key("displayName"): userData['full_name'] = self.infos["displayName"] if self.infos.has_key("password"): userData['password'] = self.infos["password"] userData['flags'] = win32netcon.UF_DONT_EXPIRE_PASSWD userData['flags'] |= win32netcon.UF_NORMAL_ACCOUNT userData['flags'] |= win32netcon.UF_PASSWD_CANT_CHANGE userData['flags'] |= win32netcon.UF_SCRIPT userData['priv'] = win32netcon.USER_PRIV_USER userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS userData['password_expired'] = 0 # password never expire userData['acct_expires'] = win32netcon.TIMEQ_FOREVER try: win32net.NetUserAdd(None, 3, userData) except Exception, e: Logger.error("unable to create user: "+str(e)) raise e
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
def getUsersGroup(): try: sid = win32security.ConvertStringSidToSid("S-1-5-32-555") name, _, _ = win32security.LookupAccountSid(None, sid) except Exception, err: Logger.error("TS::getUsersGroup unable to found remote users group replacing by default name") return "Remote Desktop Users"
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
def getIcon(self, id_): doc = Document() rootNode = doc.createElement('application') rootNode.setAttribute("id", id_) doc.appendChild(rootNode) response = self.communictionInstance.send_packet("/application/icon", doc) if response is False or not response.headers.has_key("Content-Type"): return False contentType = response.headers["Content-Type"].split(";")[0] if not contentType == "image/png": Logger.error("content type: %s"%(contentType)) print response.read() return None data = response.read() path = os.path.join(self.spool, id_+".png") try: f= file(path, "wb") except: Logger.error("Unable to open file '%s'"%(path)) return False f.write(data) f.close() return True
def destroy(self): sid = self.getSid() if sid is None: return succefulDelete = False try: win32profile.DeleteProfile(sid) succefulDelete = True except: pass if not succefulDelete: if not self.unload(sid): Logger.error("Unable to unload User reg key for user %s"%(self.name)) return False try: win32profile.DeleteProfile(sid) succefulDelete = True except Exception, e: Logger.warn("Unable to unload user reg: %s"%(str(e))) try: path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%s"%(sid) Reg.DeleteTree(win32con.HKEY_LOCAL_MACHINE, path) except Exception, err: Logger.warn("RegDeleteTree of %s return: %s"%(path, str(err))) return False
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
def createShortcut(self, application_): lines = [] lines.append("[Desktop Entry]") lines.append("Type=Application") lines.append("Terminal=false") lines.append("Version=1.0") lines.append("Icon=%s"%(os.path.join(self.spool, application_["id"]+".png"))) lines.append("Name=%s"%(application_["name"])) lines.append("Comment=%s"%(application_["description"])) lines.append("Exec=%s"%(application_["command"])) lines.append("MimeType=%s"%(";".join(application_["mimetypes"]))) #parser = ConfigParser.ConfigParser() #parser.add_section("Desktop Entry") #parser.set("Desktop Entry", "Type", "Application") #parser.set("Desktop Entry", "Version", "1.0") #parser.set("Desktop Entry", "Terminal", "false") #parser.set("Desktop Entry", "Icon", os.path.join(self.spool, application_["id"]+".png")) #parser.set("Desktop Entry", "Name", application_["name"]) #parser.set("Desktop Entry", "Comment", application_["description"]) #parser.set("Desktop Entry", "Exec", application_["command"]) #parser.set("Desktop Entry", "MimeType", ";".join(application_["mimetypes"])) path = os.path.join(self.spool, application_["id"]+".desktop") try: f= file(path, "w") except: Logger.error("Unable to open file '%s'"%(path)) return False f.writelines([s+"\n" for s in lines]) #parser.write(f) f.close() return True
def destroy(self): lock = FileLock("/tmp/user.lock") arg_remove = "" if self.check_remaining_mount_points(): arg_remove = "--remove" cmd = "userdel --force %s %s"%(arg_remove, System.local_encode(self.name)) retry = 5 while retry !=0: lock.acquire() s,o = commands.getstatusoutput(cmd) lock.release() if s == 0: return True if s == 3072: Logger.debug("mail dir error: '%s' return %d => %s"%(str(cmd), s, o)) return True Logger.debug("User delete of %s: retry %i"%(self.name, 6-retry)) if s == 256 or s == 2560: # an other process is creating a user Logger.debug("An other process is creating a user") retry -=1 time.sleep(0.2) continue if s != 0: Logger.error("userdel return %d (%s)"%(s, o)) return False return True
def createShortcut(self, application_): lines = [] lines.append("[Desktop Entry]") lines.append("Type=Application") lines.append("Terminal=false") lines.append("Version=1.0") lines.append("Icon=%s" % (os.path.join(self.spool, application_["id"] + ".png"))) lines.append("Name=%s" % (application_["name"])) lines.append("Comment=%s" % (application_["description"])) lines.append("Exec=%s" % (application_["command"])) lines.append("MimeType=%s" % (";".join(application_["mimetypes"]))) #parser = ConfigParser.ConfigParser() #parser.add_section("Desktop Entry") #parser.set("Desktop Entry", "Type", "Application") #parser.set("Desktop Entry", "Version", "1.0") #parser.set("Desktop Entry", "Terminal", "false") #parser.set("Desktop Entry", "Icon", os.path.join(self.spool, application_["id"]+".png")) #parser.set("Desktop Entry", "Name", application_["name"]) #parser.set("Desktop Entry", "Comment", application_["description"]) #parser.set("Desktop Entry", "Exec", application_["command"]) #parser.set("Desktop Entry", "MimeType", ";".join(application_["mimetypes"])) path = os.path.join(self.spool, application_["id"] + ".desktop") try: f = file(path, "w") except: Logger.error("Unable to open file '%s'" % (path)) return False f.writelines([s + "\n" for s in lines]) #parser.write(f) f.close() return True
def destroy(self): lock = FileLock("/tmp/user.lock") arg_remove = "" if self.check_remaining_mount_points(): arg_remove = "--remove" cmd = "userdel --force %s %s"%(arg_remove, System.local_encode(self.name)) retry = 5 while retry !=0: lock.acquire() p = System.execute(cmd) lock.release() if p.returncode == 0: return True if p.returncode == 12: Logger.debug("mail dir error: '%s' return %d => %s"%(str(cmd), p.returncode, p.stdout.read())) return True Logger.debug("User delete of %s: retry %i"%(self.name, 6-retry)) if p.returncode == 1 or p.returncode == 10: # 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("userdel return %d (%s)"%(p.returncode, p.stdout.read())) return False return True
def destroy(self): sid = self.getSid() if sid is None: return succefulDelete = False try: win32profile.DeleteProfile(sid) succefulDelete = True except: pass if not succefulDelete: if not self.unload(sid): Logger.error("Unable to unload User reg key for user %s" % (self.name)) return False try: win32profile.DeleteProfile(sid) succefulDelete = True except Exception, e: Logger.warn("Unable to unload user reg: %s" % (str(e))) try: path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%s" % ( sid) Reg.DeleteTree(win32con.HKEY_LOCAL_MACHINE, path) except Exception, err: Logger.warn("RegDeleteTree of %s return: %s" % (path, str(err))) return False
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
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
def start(self): self.path["spool"] = Config.spool self.path["spool.real"] = Config.spool+".real" if os.path.ismount(self.path["spool"]): Logger.warn("Failed to start FS backend, %s is already mounted"%(self.path["spool"])) return False for p in self.path: path = self.path[p] try: os.makedirs(path) except OSError, err: if err[0] is not errno.EEXIST: Logger.exception("Failed to create spool directory: %s"%path) return False try: os.lchown(path, Config.uid, Config.gid) except OSError: Logger.exception("Unable to change file owner for '%s'"%path) return False if not os.path.exists(path): Logger.error("Spool directory %s do not exist"%(path)) return False
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
def update_shares(self, share, quota, toAdd): if self.pid is None: try: f = open(self.pidFile, "r") pidStr = f.readline() if len(pidStr) == 0: Logger.error("Invalid FSBackend pid: %s"%(pidStr)) return False self.pid = int(pidStr) except Exception: Logger.exception("Failed to get FSBackend pid") return False try: # TODO use a file lock f = open(self.sharesFile, "rw") lines = f.readlines() out = "" found = False f.close() for line in lines: compo = line.split(',') if len(compo) != 2: # Check comment strippedLine = line.strip() if strippedLine.startswith("#") or strippedLine.startswith(";") or len(strippedLine) == 0: out += line continue Logger.error("The following line '%s' is not properly formated, removing it"%(line)) continue if share == compo[0].strip(): if toAdd: # updating entry out += "%s, %s\n"%(share, quota) found = True continue # we restore the entry out += line if not found and toAdd: # we append a new entry out += "%s, %s\n"%(share, quota) f = open(self.sharesFile, "w+") f.write(out) f.close() # force share data relaod os.kill(self.pid, signal.SIGHUP) return True except Exception: Logger.exception("Failed to add entry for the share '%s'"%share) return False
def init(self): Logger.info("Gateway init") if version[0] != 2 or version[1] < 6 or (version[1] == 7 and version[2] in [1, 2]): Logger.error("Gateway:: incompatibility with current Python machine '%d.%d.%d'" % version[:3]) return False fpem = os.path.join(Config.general.conf_dir, "gateway.pem") if os.path.exists(fpem): self.ssl_ctx = SSL.Context(SSL.SSLv23_METHOD) self.ssl_ctx.use_privatekey_file(fpem) self.ssl_ctx.use_certificate_file(fpem) self.ssl_ctx.load_verify_locations(fpem) if Config.disable_sslv2: self.ssl_ctx.set_options(SSL.OP_NO_SSLv2) else: Logger.error("Gateway role need a certificate (%s)" % fpem) return False addr = (Config.address, Config.port) try: GatewayTCPHandler.role = self self.server = GatewayTCPServer(addr, GatewayTCPHandler, bind_and_activate=False) self.server.allow_reuse_address = Config.general.server_allow_reuse_address self.server.server_bind() self.server.server_activate() except socket.error: Logger.exception("Gateway:: socket init") return False Logger.info('Gateway:: running on (%s, %d)' % addr) return True
def onSessionCreate(self): if not self.session.user.exists(): Logger.error("Unable to create session for user '%s': user doesn't not exists and use local users ..."%(self.session.user.name)) return False self.groups_before_ovd_session = self.session.user.get_groups() if self.groups_before_ovd_session is None: return False groups = set(self.ovd_session_required_groups + self.groups_before_ovd_session) if not self.session.user.set_groups(groups): Logger.error("Failed to customize groups of the user %s"%(self.session.user.name)) return False if self.force_local_password: if Config.override_password_method is Config.OVERRIDE_PASSWORD_METHOD_CUSTOM: ret = self.session.user.set_custom_password() else: ret = self.session.user.set_password() if not ret: return False if not self.session.install_client(): return False return True
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
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()) )
def initialize(self): if os.path.exists(self.socket_filename): try: os.remove(self.socket_filename) except Exception, e: Logger.error("Unable to initialize Communication: %s"%(str(e))) return False
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)
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()))
def get_by_id(cls, app_id): if cls._instance is None: Logger.error('[WebApps] using not initialized ApplicationsRepository') for app_def in cls._instance.process('_list'): if app_def.id == app_id: return app_def
def uninstall_client(self): if not self.succefully_initialized: return self.archive_shell_dump() if self.profile is not None and self.profile.hasProfile(): if not self.profile.mount(): Logger.warn("Unable to mount profile at uninstall_client of session " + self.id) else: self.profile.copySessionStop() desktop_path = os.path.join(self.profile.mountPoint, self.profile.DesktopDir) self.cleanupShortcut(desktop_path) for shortcut in self.installedShortcut: dstFile = os.path.join(self.profile.mountPoint, self.profile.DesktopDir, shortcut) if os.path.exists(dstFile): os.remove(dstFile) if not self.profile.umount(): Logger.error("Unable to umount profile at uninstall_client of session " + self.id) self.domain.onSessionEnd() return True
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
def readable(self): if time.time() - self.lastPacketTime > Config.connection_timeout: Logger.error("HttpProtocolDetectDispatcher::connection timeout") self.handle_close() return False return True
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
def create(self): userData = {} userData['name'] = self.name if self.infos.has_key("displayName"): userData['full_name'] = self.infos["displayName"] if self.infos.has_key("password"): userData['password'] = self.infos["password"] userData['flags'] = win32netcon.UF_DONT_EXPIRE_PASSWD userData['flags'] |= win32netcon.UF_NORMAL_ACCOUNT userData['flags'] |= win32netcon.UF_PASSWD_CANT_CHANGE userData['flags'] |= win32netcon.UF_SCRIPT userData['priv'] = win32netcon.USER_PRIV_USER userData['primary_group_id'] = ntsecuritycon.DOMAIN_GROUP_RID_USERS userData['password_expired'] = 0 # password never expire userData['acct_expires'] = win32netcon.TIMEQ_FOREVER if self.infos.has_key("locale"): userData['country_code'] = Langs.getLCID(self.infos["locale"]) try: win32net.NetUserAdd(None, 3, userData) except Exception, e: Logger.error("unable to create user: " + str(e)) return False
def groupMember(name_): try: (users, _, _) = win32net.NetLocalGroupGetMembers(None, name_, 1) except win32net.error, e: Logger.error("groupMember: '%s'" % (str(e))) return None
def onSessionCreate(self): if not self.session.user.exists(): Logger.error( "Unable to create session for user '%s': user doesn't not exists and use local users ..." % (self.session.user.name)) return False self.groups_before_ovd_session = self.session.user.get_groups() if self.groups_before_ovd_session is None: return False groups = set(self.ovd_session_required_groups + self.groups_before_ovd_session) if not self.session.user.set_groups(groups): Logger.error("Failed to customize groups of the user %s" % (self.session.user.name)) return False if self.force_local_password: if Config.override_password_method is Config.OVERRIDE_PASSWORD_METHOD_CUSTOM: ret = self.session.user.set_custom_password() else: ret = self.session.user.set_password() if not ret: return False if not self.session.install_client(): return False return True
def userRemove(user_): try: win32net.NetUserDel(None, user_) except win32net.error, e: Logger.error("userRemove: '%s'" % (str(e))) return False
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
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"])
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
def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # Give the multiprocessing module a python interpreter to run if sys.argv[0].endswith("exe"): basedir = os.path.dirname(sys.argv[0]) multiprocessing.set_executable(os.path.join(basedir, "ulteo-ovd-slaveserver.exe")) # Init the logger instance Win32Logger.initialize("OVD", Config.log_level, None) ConfigModule.report_error = WinReport_error config_file = os.path.join(Platform.System.get_default_config_dir(), "slaveserver.conf") if not Config.read(config_file): Logger.error("invalid configuration file '%s'"%(config_file)) sys.exit(1) if not Config.is_valid(): Logger.error("invalid config") sys.exit(1) Win32Logger.initialize("OVD", Config.log_level, Config.log_file) SlaveServer.__init__(self, Communication) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def destroy(self): lock = FileLock("/tmp/user.lock") arg_remove = "" if self.check_remaining_mount_points(): arg_remove = "--remove" cmd = "userdel --force %s %s" % (arg_remove, System.local_encode(self.name)) retry = 5 while retry != 0: lock.acquire() p = System.execute(cmd) lock.release() if p.returncode == 0: return True if p.returncode == 12: Logger.debug("mail dir error: '%s' return %d => %s" % (str(cmd), p.returncode, p.stdout.read())) return True Logger.debug("User delete of %s: retry %i" % (self.name, 6 - retry)) if p.returncode == 1 or p.returncode == 10: # 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("userdel return %d (%s)" % (p.returncode, p.stdout.read())) return False return True
def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) #win32evtlogutil.ReportEvent(self.log_type, 2, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE, strings=["Message d'arret"]) if not SlaveServer.init(self): Logger.error("Unable to initialize SlaveServer") SlaveServer.stop(self) return self.ReportServiceStatus(win32service.SERVICE_RUNNING) inited = False rc = win32event.WAIT_TIMEOUT while rc == win32event.WAIT_TIMEOUT: if not inited: ret = SlaveServer.push_production(self) if ret: inited = True Logger.info("SlaveServer started") else: Logger.warn("Session Manager not connected. Sleeping for a while ...") if inited: SlaveServer.loop_procedure(self) rc = win32event.WaitForSingleObject(self.hWaitStop, 30 * 1000) if not self.stopped: SlaveServer.stop(self) Logger.info("SlaveServer stopped")
def init(infos): if infos.has_key("thread_count"): value = infos["thread_count"] if value.lower() == "auto": Config.thread_count = None else: try: nbThread = int(value) except ValueError: Logger.error("Invalid int number for thread_count") nbThread = 1 if nbThread <= 0: Logger.error("thread_count must be greater than 0") else: Config.thread_count = nbThread if infos.has_key("checkshell"): Config.checkShell = (infos["checkshell"].lower() == "true") if infos.has_key("clean_dump_archive"): Config.clean_dump_archive = ( infos["clean_dump_archive"].lower() == True) return True
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
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
def groupMember(name_): try: (users, _, _) = win32net.NetLocalGroupGetMembers(None, name_, 1) except win32net.error, e: Logger.error("groupMember: '%s'"%(str(e))) return None
def req_sendip(self, request): try: document = minidom.parseString(request["data"]) rootNode = document.documentElement if rootNode.nodeName != "vm": raise Exception("invalid root node") except: Logger.error("Invalid input XML") doc = Document() rootNode = doc.createElement("error") rootNode.setAttribute("reason", "Invalid input XML") doc.appendChild(rootNode) response = self.send_packet("/vm/info", document) if response is False: Logger.warn( "DialogHypVM::send_ip unable to send request to the session manager" ) return False return self.req_answer(document)
def userRemove(user_): try: win32net.NetUserDel(None, user_) except win32net.error, e: Logger.error("userRemove: '%s'"%(str(e))) return False
def start(self): self.path["spool"] = Config.spool self.path["spool.real"] = Config.spool + ".real" if os.path.ismount(self.path["spool"]): Logger.warn("Failed to start FS backend, %s is already mounted" % (self.path["spool"])) return False for p in self.path: path = self.path[p] try: os.makedirs(path) except OSError, err: if err[0] is not errno.EEXIST: Logger.exception("Failed to create spool directory: %s" % path) return False try: os.lchown(path, Config.uid, Config.gid) except OSError: Logger.exception("Unable to change file owner for '%s'" % path) return False if not os.path.exists(path): Logger.error("Spool directory %s do not exist" % (path)) return False
def process(self, func_name, *args, **kwargs): self.lock.acquire() try: ## send message to start operation if self.queue_in is None: Logger.error('[WebApps] using not initialized SessionsRepository') return try: self.queue_in.put((func_name, args, kwargs)) except (EOFError, socket.error): Logger.exception('[WebApps] error when running {0}'.format(func_name)) return ## wait for response while True: try: result = self.queue_out.get(True, 5) except Queue.Empty, e: Logger.error('[WebApps] no response from SessionsRepository') break else: return result finally: self.lock.release()
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
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