def load_icon_from_file(filename): if filename.endswith("xpm"): try: from xpra.gtk_common.gobject_compat import import_pixbufloader from xpra.gtk_common.gtk_util import pixbuf_save_to_memory data = load_binary_file(filename) loader = import_pixbufloader()() loader.write(data) loader.close() pixbuf = loader.get_pixbuf() pngicondata = pixbuf_save_to_memory(pixbuf, "png") return pngicondata, "png" except Exception as e: log("pixbuf error loading %s", filename, exc_info=True) log.error("Error loading '%s':", filename) log.error(" %s", e) #try PIL: from PIL import Image try: img = Image.open(filename) except Exception as e: log("Image.open(%s)", filename, exc_info=True) log.error("Error loading '%s':", filename) log.error(" %s", e) return None buf = BytesIOClass() img.save(buf, "PNG") pngicondata = buf.getvalue() buf.close() return pngicondata, "png" icondata = load_binary_file(filename) if not icondata: return None log("got icon data from '%s': %i bytes", filename, len(icondata)) return icondata, os.path.splitext(filename)[1].rstrip(".")
def get_encryption_key(self): key = load_binary_file(self.encryption_keyfile) if key is None and self.password_file: key = load_binary_file(self.password_file) if key: log("used password file as encryption key") if key is None: raise Exception("failed to load encryption keyfile %s" % self.encryption_keyfile) return key.strip("\n\r")
def load_icon_from_file(filename): log("load_icon_from_file(%s)", filename) if filename.endswith("xpm"): from PIL import Image try: img = Image.open(filename) buf = BytesIO() img.save(buf, "PNG") pngicondata = buf.getvalue() buf.close() return pngicondata, "png" except ValueError as e: log("Image.open(%s)", filename, exc_info=True) except Exception as e: log("Image.open(%s)", filename, exc_info=True) log.error("Error loading '%s':", filename) log.error(" %s", e) #fallback to PixbufLoader: try: from xpra.gtk_common.gtk_util import pixbuf_save_to_memory data = load_binary_file(filename) from gi.repository import GdkPixbuf loader = GdkPixbuf.PixbufLoader() loader.write(data) loader.close() pixbuf = loader.get_pixbuf() pngicondata = pixbuf_save_to_memory(pixbuf, "png") return pngicondata, "png" except Exception as e: log("pixbuf error loading %s", filename, exc_info=True) log.error("Error loading '%s':", filename) log.error(" %s", e) icondata = load_binary_file(filename) if not icondata: return None if filename.endswith("svg") and len(icondata)>MAX_ICON_SIZE//2: #try to resize it size = len(icondata) pngdata = svg_to_png(filename, icondata) if pngdata: log("reduced size of SVG icon %s, from %i bytes to %i bytes as PNG", filename, size, len(pngdata)) icondata = pngdata filename = filename[:-3]+"png" log("got icon data from '%s': %i bytes", filename, len(icondata)) if len(icondata)>MAX_ICON_SIZE and first_time("icon-size-warning-%s" % filename): global large_icons large_icons.append((filename, len(icondata))) return icondata, os.path.splitext(filename)[1].lstrip(".")
def get_encryption_key(self): key = load_binary_file(self.encryption_keyfile) if not key: key = os.environ.get('XPRA_ENCRYPTION_KEY') if not key and self.password_file: key = load_binary_file(self.password_file) if key: log("used password file as encryption key") if not key: key = os.environ.get('XPRA_PASSWORD') if key: log("used XPRA_PASSWORD as encryption key") if key is None: raise Exception("no encryption key") return key.strip("\n\r")
def get_encryption_key(self): key = load_binary_file(self.encryption_keyfile) if not key: key = os.environ.get('XPRA_ENCRYPTION_KEY') if not key: raise InitExit(1, "no encryption key") return key.strip("\n\r")
def get_CUDA_function(device_id, function_name): """ Returns the compiled kernel for the given device and kernel key. """ global KERNELS data = KERNELS.get(function_name) if data is None: from xpra.platform.paths import get_resources_dir cubin_file = os.path.join(get_resources_dir(), "cuda", "%s.fatbin" % function_name) log("get_CUDA_function(%s, %s) cubin file=%s", device_id, function_name, cubin_file) data = load_binary_file(cubin_file) if not data: log.error("Error: failed to load CUDA bin file '%s'", cubin_file) return None log(" loaded %s bytes", len(data)) KERNELS[function_name] = data #now load from cubin: start = monotonic_time() try: mod = driver.module_from_buffer(data) except Exception as e: log("module_from_buffer(%s)", data, exc_info=True) log.error("Error: failed to load module from buffer for '%s'", function_name) log.error(" %s", e) return None log("get_CUDA_function(%s, %s) module=%s", device_id, function_name, mod) try: fn = function_name CUDA_function = mod.get_function(fn) except driver.LogicError as e: raise Exception("failed to load '%s' from %s: %s" % (function_name, mod, e)) from None end = monotonic_time() log("loading function %s from pre-compiled cubin took %.1fms", function_name, 1000.0*(end-start)) return CUDA_function
def get_CUDA_function(device_id, function_name): """ Returns the compiled kernel for the given device and kernel key. """ global KERNELS data = KERNELS.get(function_name) if data is None: from xpra.platform.paths import default_get_app_dir from xpra.os_util import load_binary_file cubin_file = os.path.join(default_get_app_dir(), "cuda", "%s.fatbin" % function_name) log("get_CUDA_function(%s, %s) cubin file=%s", device_id, function_name, cubin_file) data = load_binary_file(cubin_file) if not data: log.error("failed to load CUDA bin file %s", cubin_file) return None log(" loaded %s bytes", len(data)) KERNELS[function_name] = data #now load from cubin: start = time.time() mod = driver.module_from_buffer(data) log("get_CUDA_function(%s, %s) module=%s", device_id, function_name, mod) try: CUDA_function = mod.get_function(function_name) except driver.LogicError as e: raise Exception("failed to load '%s' from %s: %s" % (function_name, mod, e)) end = time.time() log("loading function %s from pre-compiled cubin took %.1fms", function_name, 1000.0*(end-start)) return CUDA_function
def get_proc_cmdline(pid): if pid and LINUX: #try to find the command via /proc: proc_cmd_line = os.path.join("/proc", "%s" % pid, "cmdline") if os.path.exists(proc_cmd_line): return load_binary_file(proc_cmd_line).rstrip(b"\0") return None
def _process_request_file(self, proto, packet): ss = self.get_server_source(proto) if not ss: printlog.warn("Warning: invalid client source for send-data-response packet") return argf = u(packet[1]) openit = packet[2] filename = os.path.abspath(osexpand(argf)) if not os.path.exists(filename): filelog.warn("Warning: the file requested does not exist:") filelog.warn(" %s", filename) ss.may_notify(XPRA_FILETRANSFER_NOTIFICATION_ID, "File not found", "The file requested does not exist:\n%s" % filename, icon_name="file") return try: stat = os.stat(filename) filelog("os.stat(%s)=%s", filename, stat) except os.error: filelog("os.stat(%s)", filename, exc_info=True) else: file_size = stat.st_size if file_size>self.file_transfer.file_size_limit or file_size>ss.file_size_limit: ss.may_notify(XPRA_FILETRANSFER_NOTIFICATION_ID, "File too large", "The file requested is too large to send:\n%s\nis %s" % (argf, std_unit(file_size)), icon_name="file") return data = load_binary_file(filename) ss.send_file(filename, "", data, len(data), openit=openit, options={"request-file" : (argf, openit)})
def get_CUDA_function(device_id, function_name): """ Returns the compiled kernel for the given device and kernel key. """ global KERNELS data = KERNELS.get(function_name) if data is None: from xpra.platform.paths import default_get_app_dir from xpra.os_util import load_binary_file cubin_file = os.path.join(default_get_app_dir(), "cuda", "%s.fatbin" % function_name) log("get_CUDA_function(%s, %s) cubin file=%s", device_id, function_name, cubin_file) data = load_binary_file(cubin_file) if not data: log.error("failed to load CUDA bin file %s", cubin_file) return None log(" loaded %s bytes", len(data)) KERNELS[function_name] = data #now load from cubin: start = time.time() mod = driver.module_from_buffer(data) log("get_CUDA_function(%s, %s) module=%s", device_id, function_name, mod) try: CUDA_function = mod.get_function(function_name) except driver.LogicError as e: raise Exception("failed to load '%s' from %s: %s" % (function_name, mod, e)) end = time.time() log("loading function %s from pre-compiled cubin took %.1fms", function_name, 1000.0 * (end - start)) return CUDA_function
def do_test_control_send_file(self, data): f = self._temp_file(data) try: display = self.find_free_display() server = self.check_start_server(display) xvfb, client = self.run_client(display, "--file-transfer=yes") assert pollwait(client, CLIENT_TIMEOUT) is None #send a file to this client: send_file_command = [ "control", display, "send-file", f.name, "0", "*" ] send_file = self.run_xpra(send_file_command) assert pollwait( send_file, CLIENT_TIMEOUT ) == 0, "send-file command returncode is %s" % send_file.poll() time.sleep(1) #now verify the file can be found in the download directory from xpra.platform.paths import get_download_dir filename = os.path.join(os.path.expanduser(get_download_dir()), os.path.basename(f.name)) assert os.path.exists(filename), "cannot find %s" % filename readback = load_binary_file(filename) assert readback == data, "file data corrupted" os.unlink(filename) #cleanup: client.terminate() xvfb.terminate() server.terminate() finally: f.close()
def do_control_file_command(self, command_type, client_uuids, filename, source_flag_name, send_file_args): #find the clients: sources = self._control_get_sources(client_uuids) if not sources: raise ControlError("no clients found matching: %s" % client_uuids) #find the file and load it: actual_filename = os.path.abspath(os.path.expanduser(filename)) try: stat = os.stat(actual_filename) log("os.stat(%s)=%s", actual_filename, stat) except os.error: log("os.stat(%s)", actual_filename, exc_info=True) if not os.path.exists(actual_filename): raise ControlError("file '%s' does not exist" % filename) data = load_binary_file(actual_filename) #verify size: file_size = len(data) file_size_MB = file_size//1024//1024 if file_size_MB>self.file_transfer.file_size_limit: raise ControlError("file '%s' is too large: %iMB (limit is %iMB)" % ( filename, file_size_MB, self.file_transfer.file_size_limit)) #send it to each client: for ss in sources: #ie: ServerSource.file_transfer (found in FileTransferAttributes) if not getattr(ss, source_flag_name): log.warn("Warning: cannot %s '%s'", command_type, filename) log.warn(" client %s does not support this feature", ss) elif file_size_MB>ss.file_size_limit: log.warn("Warning: cannot %s '%s'", command_type, filename) log.warn(" client %s file size limit is %iMB (file is %iMB)", ss, ss.file_size_limit, file_size_MB) else: ss.send_file(filename, "", data, file_size, *send_file_args) return "%s of '%s' to %s initiated" % (command_type, filename, client_uuids)
def set_command_args(self, command): log("set_command_args(%s)", command) self.filename = command[0] #print command arguments: #filename, file_data, mimetype, source_uuid, title, printer, no_copies, print_options_str = packet[1:9] self.command = command[1:] #TODO: load as needed... def sizeerr(size): self.warn_and_quit(EXIT_FILE_TOO_BIG, "the file is too large: %iMB (the file size limit is %iMB)" % (size//1024//1024, self.file_size_limit)) return if self.filename=="-": #replace with filename proposed self.filename = command[2] #read file from stdin self.file_data = sys.stdin.read() log("read %i bytes from stdin", len(self.file_data)) else: import os.path size = os.path.getsize(self.filename) if size>self.file_size_limit*1024*1024: sizeerr(size) return from xpra.os_util import load_binary_file self.file_data = load_binary_file(self.filename) log("read %i bytes from %s", len(self.file_data), self.filename) size = len(self.file_data) if size>self.file_size_limit*1024*1024: sizeerr(size) return assert self.file_data, "no data found for '%s'" % self.filename
def load_password(self): if not self.password_file: return os.environ.get('XPRA_PASSWORD') filename = os.path.expanduser(self.password_file) password = load_binary_file(filename) netlog("password read from file %s is %s", self.password_file, "".join(["*" for _ in (password or "")])) return password
def get_property(self, prop): #subclasses can define properties as attributes: attr_name = prop.replace("-", "_") if hasattr(self, attr_name): return getattr(self, attr_name) #otherwise fallback to default behaviour: if prop == "title": return prettify_plug_name( self.window.get_screen().get_display().get_name()) if prop == "client-machine": return socket.gethostname() if prop == "window-type": return ["NORMAL"] if prop == "fullscreen": return False if prop == "shadow": return True if prop == "depth": return 24 if prop == "scaling": return None if prop == "opacity": return None if prop == "size-hints": size = self.get_dimensions() return { "maximum-size": size, "minimum-size": size, "base-size": size, } if prop == "class-instance": osn = do_get_generic_os_name() if osn == "Linux": try: osn += "-" + get_linux_distribution()[0].replace(" ", "-") except Exception: # pragma: no cover pass return ("xpra-%s" % osn.lower(), "Xpra %s" % osn.replace("-", " ")) if prop == "icons": try: icon_name = get_icon_filename( (get_generic_os_name() or "").lower() + ".png") from PIL import Image img = Image.open(icon_name) log("Image(%s)=%s", icon_name, img) if img: icon_data = load_binary_file(icon_name) assert icon_data w, h = img.size img.close() icon = (w, h, "png", icon_data) icons = (icon, ) return icons except Exception: # pragma: no cover log("failed to return window icon") return () if prop == "content-type": return "desktop" raise ValueError("invalid property: %s" % prop)
def load_password(self): filename = os.path.expanduser(self.password_file) password = load_binary_file(filename) if password is None: return None password = password.strip("\n\r") log("password read from file %s is %s", self.password_file, "".join(["*" for _ in password])) return password
def get_default_systemd_run(): #don't use systemd-run on CentOS / RedHat #(it causes failures with "Failed to create bus connection: No such file or directory") from xpra.os_util import load_binary_file, strtobytes data = strtobytes(load_binary_file("/etc/redhat-release") or "") if data and (data.find(b"RedHat")>=0 or data.find(b"CentOS")>=0): return "no" return "auto"
def test_ssl_socket(self): server = None display_no = self.find_free_display_no() display = ":%s" % display_no tcp_port = get_free_tcp_port() ssl_port = get_free_tcp_port() try: tmpdir = tempfile.mkdtemp(suffix='ssl-xpra') certfile = os.path.join(tmpdir, "self.pem") openssl_command = [ "openssl", "req", "-new", "-newkey", "rsa:4096", "-days", "2", "-nodes", "-x509", "-subj", "/C=US/ST=Denial/L=Springfield/O=Dis/CN=localhost", "-keyout", certfile, "-out", certfile, ] openssl = self.run_command(openssl_command) assert pollwait(openssl, 10)==0, "openssl certificate generation failed" cert_data = load_binary_file(certfile) log("generated cert data: %s", repr_ellipsized(cert_data)) if not cert_data: #cannot run openssl? (happens from rpmbuild) log.warn("SSL test skipped, cannot run '%s'", b" ".join(openssl_command)) return server_args = [ "--bind-tcp=0.0.0.0:%i" % tcp_port, "--bind-ssl=0.0.0.0:%i" % ssl_port, "--ssl=on", "--ssl-cert=%s" % certfile] log("starting test ssl server on %s", display) server = self.start_server(display, *server_args) #test it with openssl client: for port in (tcp_port, ssl_port): openssl_verify_command = "openssl s_client -connect 127.0.0.1:%i -CAfile %s < /dev/null" % (port, certfile) openssl = self.run_command(openssl_verify_command, shell=True) assert pollwait(openssl, 10)==0, "openssl certificate verification failed" def test_connect(uri, exit_code, *client_args): cmd = ["info", uri] + list(client_args) client = self.run_xpra(cmd) r = pollwait(client, 5) if client.poll() is None: client.terminate() assert r==exit_code, "expected info client to return %s but got %s" % (exit_code, client.poll()) noverify = "--ssl-server-verify-mode=none" #connect to ssl socket: test_connect("ssl/127.0.0.1:%i/" % ssl_port, EXIT_OK, noverify) #tcp socket should upgrade: test_connect("ssl/127.0.0.1:%i/" % tcp_port, EXIT_OK, noverify) #self signed cert should fail without noverify: test_connect("ssl/127.0.0.1:%i/" % ssl_port, EXIT_CONNECTION_LOST) test_connect("ssl/127.0.0.1:%i/" % tcp_port, EXIT_CONNECTION_LOST) finally: shutil.rmtree(tmpdir) if server: server.terminate()
def handle(self, packet): if not self.password_file: return False filename = os.path.expanduser(self.password_file) data = load_binary_file(filename) if not data: return False self.client.send_challenge_reply(packet, data) return True
def __init__(self, **kwargs): self.app_id = kwargs.pop("app_id", APP_ID) key_hexstring = kwargs.pop("public_key", "") super().__init__(**kwargs) self.public_keys = {} key_strs = {} if key_hexstring: log("u2f_auth: public key from configuration=%s", key_hexstring) key_strs["command-option"] = key_hexstring #try to load public keys from the user conf dir(s): if getuid() == 0 and POSIX: #root: use the uid of the username specified: uid = self.get_uid() else: uid = getuid() conf_dirs = get_user_conf_dirs(uid) log("u2f: will try to load public keys from %s", csv(conf_dirs)) #load public keys: for d in conf_dirs: ed = osexpand(d) if os.path.exists(ed) and os.path.isdir(ed): pub_keyfiles = glob.glob(os.path.join(ed, "u2f*-pub.hex")) log("u2f: keyfiles(%s)=%s", ed, pub_keyfiles) for f in sorted(pub_keyfiles): key_hexstring = load_binary_file(f) if key_hexstring: key_hexstring = key_hexstring.rstrip(b" \n\r") key_strs[f] = key_hexstring log("u2f_auth: loaded public key from file '%s': %s", f, key_hexstring) #parse public key data: #pylint: disable=import-outside-toplevel from cryptography.hazmat.primitives.serialization import load_der_public_key from cryptography.hazmat.backends import default_backend for origin, key_hexstring in key_strs.items(): try: key = binascii.unhexlify(key_hexstring) except Exception as e: log("unhexlify(%s)", key_hexstring, exc_info=True) log.warn("Warning: failed to parse key '%s'", origin) log.warn(" %s", e) continue log("u2f: trying to load DER public key %s", repr(key)) if not key.startswith(PUB_KEY_DER_PREFIX): key = PUB_KEY_DER_PREFIX + key try: k = load_der_public_key(key, default_backend()) except Exception as e: log("load_der_public_key(%r)", key, exc_info=True) log.warn("Warning: failed to parse key '%s'", origin) log.warn(" %s", e) continue self.public_keys[origin] = k if not self.public_keys: raise Exception( "u2f authenticator requires at least one public key")
def process_challenge_file(self, packet): if self.password_index<len(self.password_file): password_file = self.password_file[self.password_index] self.password_index += 1 filename = os.path.expanduser(password_file) password = load_binary_file(filename) authlog("password read from file %i '%s': %s", self.password_index, password_file, obsc(password)) self.send_challenge_reply(packet, password) return True return False
def load_password(self): if not self.password_file: return os.environ.get('XPRA_PASSWORD') filename = os.path.expanduser(self.password_file) password = load_binary_file(filename) if password is None: return None password = password.strip("\n\r") log("password read from file %s is %s", self.password_file, "".join(["*" for _ in password])) return password
def handle(self, packet) -> bool: log("handle(..) password_file=%s", self.password_file) if not self.password_file: return False filename = os.path.expanduser(self.password_file) data = load_binary_file(filename) log("loaded password data from %s: %s", filename, bool(data)) if not data: return False self.client.send_challenge_reply(packet, data) return True
def load_icon_from_file(filename): log("load_icon_from_file(%s)", filename) if filename.endswith("xpm"): try: from xpra.gtk_common.gobject_compat import import_pixbufloader from xpra.gtk_common.gtk_util import pixbuf_save_to_memory data = load_binary_file(filename) loader = import_pixbufloader()() loader.write(data) loader.close() pixbuf = loader.get_pixbuf() pngicondata = pixbuf_save_to_memory(pixbuf, "png") return pngicondata, "png" except Exception as e: log("pixbuf error loading %s", filename, exc_info=True) log.error("Error loading '%s':", filename) log.error(" %s", e) #try PIL: from PIL import Image try: img = Image.open(filename) except Exception as e: log("Image.open(%s)", filename, exc_info=True) log.error("Error loading '%s':", filename) log.error(" %s", e) return None buf = BytesIO() img.save(buf, "PNG") pngicondata = buf.getvalue() buf.close() return pngicondata, "png" icondata = load_binary_file(filename) if not icondata: return None log("got icon data from '%s': %i bytes", filename, len(icondata)) if len(icondata) > MAX_ICON_SIZE and first_time( "icon-size-warning-%s" % filename): log.warn("Warning: icon is quite large (%i KB):", len(icondata) // 1024) log.warn(" '%s'", filename) return icondata, os.path.splitext(filename)[1].lstrip(".")
def auth_publickey(): log("trying public key authentication using %s", keyfiles) for keyfile_path in keyfiles: if not os.path.exists(keyfile_path): log("no keyfile at '%s'", keyfile_path) continue log("trying '%s'", keyfile_path) key = None import paramiko for pkey_classname in ("RSA", "DSS", "ECDSA", "Ed25519"): pkey_class = getattr(paramiko, "%sKey" % pkey_classname, None) if pkey_class is None: log("no %s key type", pkey_classname) continue log("trying to load as %s", pkey_classname) try: key = pkey_class.from_private_key_file(keyfile_path) log.info("loaded %s private key from '%s'", pkey_classname, keyfile_path) break except PasswordRequiredException as e: log("%s keyfile requires a passphrase; %s", keyfile_path, e) passphrase = input_pass("please enter the passphrase for %s:" % (keyfile_path,)) if passphrase: try: key = pkey_class.from_private_key_file(keyfile_path, passphrase) log.info("loaded %s private key from '%s'", pkey_classname, keyfile_path) except SSHException as e: log("from_private_key_file", exc_info=True) log.info("cannot load key from file '%s':", keyfile_path) log.info(" %s", e) break except Exception as e: log("auth_publickey() loading as %s", pkey_classname, exc_info=True) key_data = load_binary_file(keyfile_path) if key_data and key_data.find(b"BEGIN OPENSSH PRIVATE KEY")>=0 and paramiko.__version__<"2.7": log.warn("Warning: private key '%s'", keyfile_path) log.warn(" this file seems to be using OpenSSH's own format") log.warn(" please convert it to something more standard (ie: PEM)") log.warn(" so it can be used with the paramiko backend") log.warn(" or switch to the OpenSSH backend with '--ssh=ssh'") if key: log("auth_publickey using %s as %s: %s", keyfile_path, pkey_classname, keymd5(key)) try: transport.auth_publickey(username, key) except SSHException as e: log("key '%s' rejected", keyfile_path, exc_info=True) log.info("SSH authentication using key '%s' failed:", keyfile_path) log.info(" %s", e) else: if transport.is_authenticated(): break else: log.error("Error: cannot load private key '%s'", keyfile_path)
def get_encryption_key(self): key = None if os.path.exists(self.encryption_keyfile): key = load_binary_file(self.encryption_keyfile) cryptolog("get_encryption_key() loaded %i bytes from '%s'", len(key or ""), self.encryption_keyfile) if not key: XPRA_ENCRYPTION_KEY = "XPRA_ENCRYPTION_KEY" key = strtobytes(os.environ.get(XPRA_ENCRYPTION_KEY, '')) cryptolog("get_encryption_key() got %i bytes from '%s' environment variable", len(key or ""), XPRA_ENCRYPTION_KEY) if not key: raise InitExit(1, "no encryption key") return key.strip(b"\n\r")
def do_control_file_command(self, command_type, client_uuids, filename, source_flag_name, send_file_args): #find the clients: sources = self._control_get_sources(client_uuids) if not sources: raise ControlError("no clients found matching: %s" % client_uuids) def checksize(file_size): if file_size > self.file_transfer.file_size_limit: raise ControlError( "file '%s' is too large: %sB (limit is %sB)" % (filename, std_unit(file_size), std_unit(self.file_transfer.file_size_limit))) #find the file and load it: actual_filename = os.path.abspath(os.path.expanduser(filename)) try: stat = os.stat(actual_filename) log("os.stat(%s)=%s", actual_filename, stat) except os.error: log("os.stat(%s)", actual_filename, exc_info=True) else: checksize(stat.st_size) if not os.path.exists(actual_filename): raise ControlError("file '%s' does not exist" % filename) data = load_binary_file(actual_filename) if data is None: raise ControlError("failed to load '%s'" % actual_filename) #verify size: file_size = len(data) checksize(file_size) #send it to each client: for ss in sources: #ie: ServerSource.file_transfer (found in FileTransferAttributes) if not getattr(ss, source_flag_name, False): #skip the warning if the client is not interactive #(for now just check for 'top' client): if ss.client_type == "top": l = log else: l = log.warn l("Warning: cannot %s '%s' to %s client", command_type, filename, ss.client_type) l(" client %s does not support this feature", ss.uuid) elif file_size > ss.file_size_limit: log.warn("Warning: cannot %s '%s'", command_type, filename) log.warn(" client %s file size limit is %sB (file is %sB)", ss, std_unit(ss.file_size_limit), std_unit(file_size)) else: ss.send_file(filename, "", data, file_size, *send_file_args) return "%s of '%s' to %s initiated" % (command_type, filename, client_uuids)
def load_password(self): if not self.password_file: return os.environ.get('XPRA_PASSWORD') filename = os.path.expanduser(self.password_file) password = load_binary_file(filename) if password is None: return None try: password = password.decode("utf8").strip("\n\r") except: password = str(password) netlog("password read from file %s is %s", self.password_file, "".join(["*" for _ in (password or "")])) return password
def process_challenge_u2f(self, packet): digest = packet[3] if not digest.startswith(b"u2f:"): authlog("%s is not a u2f challenge", digest) return False import binascii import logging if not is_debug_enabled("auth"): logging.getLogger("pyu2f.hardware").setLevel(logging.INFO) logging.getLogger("pyu2f.hidtransport").setLevel(logging.INFO) from pyu2f import model from pyu2f.u2f import GetLocalU2FInterface dev = GetLocalU2FInterface() APP_ID = os.environ.get("XPRA_U2F_APP_ID", "Xpra") key_handle_str = os.environ.get("XPRA_U2F_KEY_HANDLE") authlog("process_challenge_u2f XPRA_U2F_KEY_HANDLE=%s", key_handle_str) if not key_handle_str: #try to load the key handle from the user conf dir(s): from xpra.platform.paths import get_user_conf_dirs info = self._protocol.get_info(False) key_handle_filenames = [] for hostinfo in ("-%s" % info.get("host", ""), ""): key_handle_filenames += [ os.path.join(d, "u2f-keyhandle%s.hex" % hostinfo) for d in get_user_conf_dirs() ] for filename in key_handle_filenames: p = osexpand(filename) key_handle_str = load_binary_file(p) authlog("key_handle_str(%s)=%s", p, key_handle_str) if key_handle_str: key_handle_str = key_handle_str.rstrip(b" \n\r") break if not key_handle_str: authlog.warn("Warning: no U2F key handle found") return False authlog("process_challenge_u2f key_handle=%s", key_handle_str) key_handle = binascii.unhexlify(key_handle_str) key = model.RegisteredKey(key_handle) #use server salt as challenge directly challenge = packet[1] authlog.info("activate your U2F device for authentication") response = dev.Authenticate(APP_ID, challenge, [key]) sig = response.signature_data client_data = response.client_data authlog("process_challenge_u2f client data=%s, signature=%s", client_data, binascii.hexlify(sig)) self.do_send_challenge_reply(bytes(sig), client_data.origin) return True
def set_command_args(self, command): log("set_command_args(%s)", command) self.filename = command[0] self.command = command[1:] #FIXME: load as needed... from xpra.os_util import load_binary_file if self.filename=="-": #replace with filename proposed self.filename = command[2] #read file from stdin self.file_data = sys.stdin.read() log("read %i bytes from stdin", len(self.file_data)) else: self.file_data = load_binary_file(self.filename) assert self.file_data, "no data found for '%s'" % self.filename
def get_proc_driver_version(): from xpra.os_util import load_binary_file proc_file = "/proc/driver/nvidia/version" v = load_binary_file(proc_file) if not v: log.warn("Warning: NVidia kernel module not installed?") log.warn(" cannot open '%s'", proc_file) return "" KSTR = "Kernel Module" p = v.find(KSTR) if not p: log.warn("unknown NVidia kernel module version") return "" v = v[p+len(KSTR):].strip().split(" ")[0] v = v.split(".") return v
def get_proc_driver_version(): from xpra.os_util import load_binary_file proc_file = "/proc/driver/nvidia/version" v = load_binary_file(proc_file) if not v: log.warn("Warning: NVidia kernel module not installed?") log.warn(" cannot open '%s'", proc_file) return () KSTR = b"Kernel Module" p = v.find(KSTR) if not p: log.warn("unknown NVidia kernel module version") return "" v = v[p+len(KSTR):].strip().split(b" ")[0] v = v.split(b".") return v
def find_session_icon(*names): icondirs = None for name in names: fn = get_icon_filename(name) if fn: data = load_binary_file(fn) if data: return data, os.path.splitext(fn)[1].lstrip(".") if icondirs is None: icondirs = get_xdg_icon_dirs() if icondirs: #v = find_icon(("categories", "apps", "places", "*"), icondirs, name) v = find_icon(("*", ), icondirs, name) if v: return v return None
def get_fallback_window_icon(): if WindowIconSource.fallback_window_icon is False: try: from xpra.platform.paths import get_icon_filename icon_filename = get_icon_filename("xpra.png") log("get_fallback_window_icon() icon filename=%s", icon_filename) assert os.path.exists(icon_filename), "xpra icon not found: %s" % icon_filename img = Image.open(icon_filename) icon_data = load_binary_file(icon_filename) icon = (img.size[0], img.size[1], "png", icon_data) WindowIconSource.fallback_window_icon = icon return icon except Exception as e: log.warn("failed to get fallback icon: %s", e) WindowIconSource.fallback_window_icon = False return WindowIconSource.fallback_window_icon
def main(): from xpra.os_util import load_binary_file if "-v" in sys.argv: log.enable_debug() sys.argv.remove("-v") if len(sys.argv)>1: for filename in sys.argv[1:]: if not os.path.exists(filename): log.warn("file argument '%s' does not exist, ignoring", filename) continue data = load_binary_file(filename) devices = do_get_pa_device_options(data, True, False) log.info("%s devices found in '%s'", len(devices), filename) print_nested_dict(devices) return i = get_info() print_nested_dict(i)
def identify_nvidia_module_version(): if os.name!="posix": return None from xpra.os_util import load_binary_file v = load_binary_file("/proc/driver/nvidia/version") if not v: log.warn("Nvidia kernel module not installed?") return [] KSTR = "Kernel Module" p = v.find(KSTR) if not p: log.warn("unknown Nvidia kernel module version") return [] v = v[p+len(KSTR):].strip().split(" ")[0] try: numver = [int(x) for x in v.split(".")] log.info("Nvidia kernel module version %s", v) return numver except Exception as e: log.warn("failed to parse Nvidia kernel module version '%s': %s", v, e) return []
def main(): from xpra.os_util import load_binary_file if "-v" in sys.argv: log.enable_debug() sys.argv.remove("-v") if len(sys.argv) > 1: for filename in sys.argv[1:]: if not os.path.exists(filename): log.warn("file argument '%s' does not exist, igoring", filename) continue data = load_binary_file(filename) devices = do_get_pa_device_options(data, True, False) log.info("%s devices found in '%s'", len(devices), filename) for d, info in devices.items(): log.info("* %s : %s", d, info) return i = get_info() for k in sorted(i): log.info("%s : %s", k.ljust(64), i[k])
def set_command_args(self, command): log("set_command_args(%s)", command) self.filename = command[0] #print command arguments: #filename, file_data, mimetype, source_uuid, title, printer, no_copies, print_options_str = packet[1:9] self.command = command[1:] #FIXME: load as needed... from xpra.os_util import load_binary_file if self.filename=="-": #replace with filename proposed self.filename = command[2] #read file from stdin self.file_data = sys.stdin.read() log("read %i bytes from stdin", len(self.file_data)) else: self.file_data = load_binary_file(self.filename) log("read %i bytes from %s", len(self.file_data), self.filename) if len(self.file_data)>=self.file_size_limit*1024*1024: self.warn_and_quit(EXIT_FILE_TOO_BIG, "the file is too large: %iMB (the file size limit is %iMB)" % (len(self.file_data)//1024//1024, self.file_size_limit)) return assert self.file_data, "no data found for '%s'" % self.filename
def validate_setup(): # very simple check: at least one ppd file exists defs = get_printer_definitions() if not defs: log.warn("Warning: no printer definitions found, cannot enable printing") return False # check for SELinux try: if os.path.exists("/sys/fs/selinux"): log("SELinux is present") from xpra.os_util import load_binary_file enforce = load_binary_file("/sys/fs/selinux/enforce") log("SELinux enforce=%s", enforce) if enforce == "1": log.warn("SELinux is running in enforcing mode") log.warn(" printer forwarding is unlikely to work without a policy") else: log("SELinux is present but not in enforcing mode") except Exception as e: log.error("Error checking for the presence of SELinux:") log.error(" %s", e) return True
def do_test_control_send_file(self, data): f = self._temp_file(data) try: display = self.find_free_display() server = self.check_start_server(display) xvfb, client = self.run_client(display) assert pollwait(client, CLIENT_TIMEOUT) is None #send a file to this client: send_file_command = ["control", display, "send-file", f.name, "1", "*"] send_file = self.run_xpra(send_file_command) assert pollwait(send_file, CLIENT_TIMEOUT)==0, "send-file command returncode is %s" % send_file.poll() #now verify the file can be found in the download directory from xpra.platform.paths import get_download_dir filename = os.path.join(os.path.expanduser(get_download_dir()), os.path.basename(f.name)) assert os.path.exists(filename), "cannot find %s" % filename readback = load_binary_file(filename) assert readback==data os.unlink(filename) #cleanup: client.terminate() xvfb.terminate() server.terminate() finally: f.close()
def filedata_nocrlf(self, filename): v = load_binary_file(filename) if v is None: log.error("failed to load '%s'", filename) return None return v.strip("\n\r")