def get_prefs(): global PREFS if PREFS is None: PREFS = {} from xpra.platform.paths import get_default_conf_dirs, get_system_conf_dirs, get_user_conf_dirs dirs = get_default_conf_dirs() + get_system_conf_dirs( ) + get_user_conf_dirs() log("get_prefs() will try to load cuda.conf from: %s", dirs) for d in dirs: conf_file = os.path.join(os.path.expanduser(d), "cuda.conf") if not os.path.exists(conf_file): log("get_prefs() '%s' does not exist!", conf_file) continue if not os.path.isfile(conf_file): log("get_prefs() '%s' is not a file!", conf_file) continue try: with open(conf_file, "rU") as f: for line in f: sline = line.strip().rstrip('\r\n').strip() props = sline.split("=", 1) if len(props) != 2: continue name = props[0].strip() value = props[1].strip() if name in ("blacklist", ): PREFS.setdefault(name, []).append(value) elif name in ("device-id", "device-name"): PREFS[name] = value except Exception as e: log.error("Error: cannot read cuda configuration file '%s':", conf_file) log.error(" %s", e) return PREFS
def read_xpra_defaults(): """ Reads the global <xpra_conf_filename> from the <conf_dir> and then the user-specific one. (the latter overrides values from the former) returns a dict with values as strings and arrays of strings. If the <conf_dir> is not specified, we figure out its location. """ from xpra.platform.paths import get_default_conf_dirs, get_system_conf_dirs, get_user_conf_dirs # load config files in this order (the later ones override earlier ones): # * application defaults (ie: "/Volumes/Xpra/Xpra.app/Contents/Resources/" on OSX) # (ie: "C:\Program Files\Xpra\" on win32) # (ie: None on others) # * system defaults (ie: "/etc/xpra" on Posix - not on OSX) # (ie: "/Library/Application Support/Xpra" on OSX) # (ie: "C:\Documents and Settings\All Users\Application Data\Xpra" with XP) # (ie: "C:\ProgramData\Xpra" with Vista onwards) # * user config (ie: "~/.xpra/" on all Posix, including OSX) # (ie: "C:\Documents and Settings\Username\Application Data\Xpra" with XP) # (ie: "C:\Users\<user name>\AppData\Roaming" with Visa onwards) dirs = get_default_conf_dirs() + get_system_conf_dirs( ) + get_user_conf_dirs() defaults = {} for d in dirs: if not d: continue ad = os.path.expanduser(d) if not os.path.exists(ad): debug("read_xpra_defaults: skipping %s", ad) continue defaults.update(read_xpra_conf(ad)) debug("read_xpra_defaults: updated defaults with %s", ad) may_create_user_config() return defaults
def get_prefs(): global PREFS if PREFS is None: PREFS = {} from xpra.platform.paths import get_default_conf_dirs, get_system_conf_dirs, get_user_conf_dirs dirs = get_default_conf_dirs() + get_system_conf_dirs() + get_user_conf_dirs() log("get_prefs() will try to load cuda.conf from: %s", dirs) for d in dirs: conf_file = os.path.join(os.path.expanduser(d), "cuda.conf") if not os.path.exists(conf_file): log("get_prefs() '%s' does not exist!", conf_file) continue if not os.path.isfile(conf_file): log("get_prefs() '%s' is not a file!", conf_file) continue try: with open(conf_file, "rU") as f: for line in f: sline = line.strip().rstrip('\r\n').strip() props = sline.split("=", 1) if len(props)!=2: continue name = props[0].strip() value = props[1].strip() if name in ("blacklist", ): PREFS.setdefault(name, []).append(value) elif name in ("device-id", "device-name"): PREFS[name] = value except Exception as e: log.error("Error: cannot read cuda configuration file '%s':", conf_file) log.error(" %s", e) return PREFS
def read_xpra_defaults(): """ Reads the global <xpra_conf_filename> from the <conf_dir> and then the user-specific one. (the latter overrides values from the former) returns a dict with values as strings and arrays of strings. If the <conf_dir> is not specified, we figure out its location. """ from xpra.platform.paths import get_default_conf_dirs, get_system_conf_dirs, get_user_conf_dirs # load config files in this order (the later ones override earlier ones): # * application defaults (ie: "/Volumes/Xpra/Xpra.app/Contents/Resources/" on OSX) # (ie: "C:\Program Files\Xpra\" on win32) # (ie: None on others) # * system defaults (ie: "/etc/xpra" on Posix - not on OSX) # (ie: "/Library/Application Support/Xpra" on OSX) # (ie: "C:\Documents and Settings\All Users\Application Data\Xpra" with XP) # (ie: "C:\ProgramData\Xpra" with Vista onwards) # * user config (ie: "~/.xpra/" on all Posix, including OSX) # (ie: "C:\Documents and Settings\Username\Application Data\Xpra" with XP) # (ie: "C:\Users\<user name>\AppData\Roaming" with Visa onwards) dirs = get_default_conf_dirs() + get_system_conf_dirs() + get_user_conf_dirs() defaults = {} for d in dirs: if not d: continue ad = os.path.expanduser(d) if not os.path.exists(ad): debug("read_xpra_defaults: skipping %s", ad) continue defaults.update(read_xpra_conf(ad)) debug("read_xpra_defaults: updated defaults with %s", ad) may_create_user_config() return defaults
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 load_categories_to_type(): categories_to_type = {} for d in get_system_conf_dirs(): v = load_content_categories_dir(os.path.join(d, "content-categories")) categories_to_type.update(v) if not POSIX or getuid() > 0: for d in get_user_conf_dirs(): load_content_categories_dir(os.path.join(d, "content-categories")) categories_to_type.update(v) return categories_to_type
def load_content_type_defs(): global content_type_defs if content_type_defs is None: content_type_defs = OrderedDict() content_type_dir = os.path.join(get_app_dir(), "content-type") log("load_content_type_defs() content_type_dir=%s", content_type_dir) load_content_type_dir(content_type_dir) for d in get_user_conf_dirs(): load_content_type_dir(d) return content_type_defs
def get_license_keys(version=0, basefilename="nvenc"): global license_keys filename = "%s%s.keys" % (basefilename, version or "") keys = license_keys.get(filename) if keys is not None: return keys env_name = "XPRA_%s_CLIENT_KEY" % basefilename.upper() env_keys = os.environ.get(env_name, "") if env_keys: keys = [x.strip() for x in env_keys.split(",")] log("using %s keys from environment variable %s: %s", basefilename, env_name, csv(keys)) else: #try to load the license file keys = [] try: #see read_xpra_defaults for an explanation of paths from xpra.platform.paths import get_default_conf_dirs, get_system_conf_dirs, get_user_conf_dirs dirs = get_default_conf_dirs() + get_system_conf_dirs( ) + get_user_conf_dirs() for d in dirs: if not d: continue keys_file = os.path.join(d, filename) keys_file = os.path.expanduser(keys_file) if not os.path.exists(keys_file): log("get_license_keys(%s, %s) '%s' does not exist", basefilename, version, keys_file) continue log("loading %s version %s keys from %s", basefilename, version, keys_file) with open(keys_file, "rb") as f: fkeys = [] for line in f: sline = bytestostr( line.strip().rstrip(b'\r\n').strip()) if not sline: log("skipping empty line") continue if sline[0] in ('!', '#'): log("skipping comments") continue fkeys.append(sline) log("added key: %s", sline) log("added %i key%s from %s", len(fkeys), engs(fkeys), keys_file) keys += fkeys except Exception: log.error("Error loading %s license keys", basefilename, exc_info=True) license_keys[filename] = keys log("get_nvenc_license_keys(%s)=%s", version, keys) return keys
def get_nvenc_license_keys(nvenc_version=0): global nvenc_license_keys keys = nvenc_license_keys.get(nvenc_version) if keys is not None: return keys env_keys = os.environ.get("XPRA_NVENC_CLIENT_KEY", "") if env_keys: keys = [ x.strip() for x in os.environ.get("XPRA_NVENC_CLIENT_KEY", "").split(",") ] log( "using nvenc keys from environment variable XPRA_NVENC_CLIENT_KEY: %s", nvenc_license_keys) else: #try the license file keys = [] try: #see read_xpra_defaults for an explanation of paths from xpra.platform.paths import get_default_conf_dirs, get_system_conf_dirs, get_user_conf_dirs dirs = get_default_conf_dirs() + get_system_conf_dirs( ) + get_user_conf_dirs() for d in dirs: if not d: continue keys_file = os.path.join( d, "nvenc%s.keys" % (nvenc_version or "")) keys_file = os.path.expanduser(keys_file) if not os.path.exists(keys_file): log("get_nvenc_license_keys(%s) '%s' does not exist", nvenc_version, keys_file) continue log("loading nvenc%s keys from %s", nvenc_version, keys_file) with open(keys_file, "rU") as f: fkeys = [] for line in f: sline = line.strip().rstrip('\r\n').strip() if len(sline) == 0: log("skipping empty line") continue if sline[0] in ('!', '#'): log("skipping comments") continue fkeys.append(sline) log("added key: %s", sline) log("added %i key%s from %s", len(fkeys), engs(fkeys), keys_file) keys += fkeys except Exception as e: log.error("error loading nvenc license keys: %s", e, exc_info=True) nvenc_license_keys[nvenc_version] = keys log("get_nvenc_license_keys(%s)=%s", nvenc_version, keys) return keys
def load_content_type_defs() -> dict: global content_type_defs if content_type_defs is None: content_type_defs = {} for d in get_system_conf_dirs(): load_content_type_dir(os.path.join(d, "content-type")) if not POSIX or getuid() > 0: for d in get_user_conf_dirs(): load_content_type_dir(os.path.join(d, "content-type")) for e in CONTENT_TYPE_DEFS.split(","): if not process_content_type_entry(e): log.warn(" invalid entry in environment variable") return content_type_defs
def load_content_type_defs(): global content_type_defs if content_type_defs is None: content_type_defs = OrderedDict() content_type_dir = os.path.join(get_app_dir(), "content-type") log("load_content_type_defs() content_type_dir=%s", content_type_dir) load_content_type_dir(content_type_dir) for d in get_user_conf_dirs(): load_content_type_dir(d) for e in CONTENT_TYPE_DEFS.split(","): if not process_content_type_entry(e): log.warn(" invalid entry in environment variable") return content_type_defs
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 get_nvenc_license_keys(nvenc_version=0): global nvenc_license_keys keys = nvenc_license_keys.get(nvenc_version) if keys is not None: return keys env_keys = os.environ.get("XPRA_NVENC_CLIENT_KEY", "") if env_keys: keys = [x.strip() for x in os.environ.get("XPRA_NVENC_CLIENT_KEY", "").split(",")] log("using nvenc keys from environment variable XPRA_NVENC_CLIENT_KEY: %s", nvenc_license_keys) else: #try the license file keys = [] try: #see read_xpra_defaults for an explanation of paths from xpra.platform.paths import get_default_conf_dirs, get_system_conf_dirs, get_user_conf_dirs dirs = get_default_conf_dirs() + get_system_conf_dirs() + get_user_conf_dirs() for d in dirs: if not d: continue keys_file = os.path.join(d, "nvenc%s.keys" % (nvenc_version or "")) keys_file = os.path.expanduser(keys_file) if not os.path.exists(keys_file): log("get_nvenc_license_keys(%s) '%s' does not exist", nvenc_version, keys_file) continue log("loading nvenc%s keys from %s", nvenc_version, keys_file) with open(keys_file, "rU") as f: fkeys = [] for line in f: sline = line.strip().rstrip('\r\n').strip() if len(sline) == 0: log("skipping empty line") continue if sline[0] in ( '!', '#' ): log("skipping comments") continue fkeys.append(sline) log("added key: %s", sline) log("added %i key%s from %s", len(fkeys), engs(fkeys), keys_file) keys += fkeys except Exception as e: log.error("error loading nvenc license keys: %s", e, exc_info=True) nvenc_license_keys[nvenc_version] = keys log("get_nvenc_license_keys(%s)=%s", nvenc_version, keys) return keys
def get_prefs(): global PREFS if PREFS is None: PREFS = {} from xpra.platform.paths import get_default_conf_dirs, get_system_conf_dirs, get_user_conf_dirs dirs = get_default_conf_dirs() + get_system_conf_dirs( ) + get_user_conf_dirs() log("get_prefs() will try to load cuda.conf from: %s", dirs) for d in dirs: conf_file = os.path.join(os.path.expanduser(d), "cuda.conf") if not os.path.exists(conf_file): log("get_prefs() '%s' does not exist!", conf_file) continue if not os.path.isfile(conf_file): log("get_prefs() '%s' is not a file!", conf_file) continue try: c_prefs = {} with open(conf_file, "rb") as f: for line in f: sline = line.strip().rstrip(b'\r\n').strip().decode( "latin1") props = sline.split("=", 1) if len(props) != 2: continue name = props[0].strip() value = props[1].strip() if name in ("enabled-devices", "disabled-devices"): for v in value.split(","): c_prefs.setdefault(name, []).append(v.strip()) elif name in ("device-id", "device-name", "load-balancing"): c_prefs[name] = value except Exception as e: log.error("Error: cannot read cuda configuration file '%s':", conf_file) log.error(" %s", e) log("get_prefs() '%s' : %s", conf_file, c_prefs) PREFS.update(c_prefs) return PREFS
def may_create_user_config(xpra_conf_filename=DEFAULT_XPRA_CONF_FILENAME): from xpra.platform.paths import get_user_conf_dirs #save a user config template: udirs = get_user_conf_dirs() if udirs: has_user_conf = None for d in udirs: if conf_files(d): has_user_conf = d break if not has_user_conf: debug("no user configuration file found, trying to create one") for d in udirs: ad = os.path.expanduser(d) conf_file = os.path.join(ad, xpra_conf_filename) try: if not os.path.exists(ad): os.makedirs(ad, int('700', 8)) with open(conf_file, 'w') as f: f.write("# xpra user configuration file\n") f.write("# place your custom settings in this file\n") f.write( "# they will take precedence over the system default ones.\n" ) f.write("\n") f.write("# Examples:\n") f.write("# speaker=off\n") f.write("# dpi=144\n") f.write("\n") f.write("# For more information on the file format,\n") f.write("# see the xpra manual at:\n") f.write("# https://xpra.org/manual.html\n") f.write("\n") f.flush() debug("created default config in " + d) break except Exception as e: debug("failed to create default config in '%s': %s" % (conf_file, e))
def get_key_handle(self) -> bytes: key_handle_str = os.environ.get("XPRA_U2F_KEY_HANDLE") log("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.client._protocol.get_info(False) key_handle_filenames = [] for hostinfo in ("-%s" % info.get("host", ""), ""): for d in get_user_conf_dirs(): key_handle_filenames.append(os.path.join(d, "u2f-keyhandle%s.hex" % hostinfo)) for filename in key_handle_filenames: p = osexpand(filename) key_handle_str = load_binary_file(p) log("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: log.warn("Warning: no U2F key handle found") return None log("process_challenge_u2f key_handle=%s", key_handle_str) return binascii.unhexlify(key_handle_str)
def may_create_user_config(xpra_conf_filename=DEFAULT_XPRA_CONF_FILENAME): from xpra.platform.paths import get_user_conf_dirs #save a user config template: udirs = get_user_conf_dirs() if udirs: has_user_conf = None for d in udirs: if conf_files(d): has_user_conf = d break if not has_user_conf: debug("no user configuration file found, trying to create one") for d in udirs: ad = os.path.expanduser(d) conf_file = os.path.join(ad, xpra_conf_filename) try: if not os.path.exists(d): os.makedirs(d, int('700', 8)) with open(conf_file, 'wb') as f: f.write("# xpra user configuration file\n") f.write("# place your custom settings in this file\n") f.write("# they will take precedence over the system default ones.\n") f.write("\n") f.write("# Examples:\n") f.write("# speaker=off\n") f.write("# dpi=144\n") f.write("\n") f.write("# For more information on the file format,\n") f.write("# see the xpra manual at:\n") f.write("# https://xpra.org/manual.html\n") f.write("\n") f.flush() debug("created default config in "+d) break except Exception as e: debug("failed to create default config in '%s': %s" % (conf_file, e))
def main(): from xpra.platform import program_context with program_context("U2F-Register", "Xpra U2F Registration Tool"): gui = not sys.stdin.isatty() or os.environ.get("MSYSCON") if gui: from xpra.gtk_common.gobject_compat import import_gtk, import_glib gtk = import_gtk() glib = import_glib() from xpra.gtk_common.gtk_util import MESSAGE_INFO, MESSAGE_ERROR, BUTTONS_CLOSE def show_dialog(mode, *msgs): dialog = gtk.MessageDialog(None, 0, mode, BUTTONS_CLOSE, "\n".join(msgs)) dialog.set_title("Xpra U2F Registration Tool") v = dialog.run() dialog.destroy() #run the main loop long enough to destroy the dialog: glib.idle_add(gtk.main_quit) gtk.main() return v def error(*msgs): return show_dialog(MESSAGE_ERROR, *msgs) def info(*msgs): return show_dialog(MESSAGE_INFO, *msgs) else: print("U2F Registration Tool") def printmsgs(*msgs): for x in msgs: print(x) error = info = printmsgs key_handle_filenames = [ os.path.join(d, "u2f-keyhandle.hex") for d in get_user_conf_dirs() ] assert len(key_handle_filenames) > 0 for filename in key_handle_filenames: p = osexpand(filename) key_handle_str = load_binary_file(p) if key_handle_str: error( " found an existing key handle in file '%s':" % p, #" %s" % key_handle_str, " skipping U2F registration", " delete this file if you want to register again") return 1 public_key_filenames = [] for d in get_user_conf_dirs(): public_key_filenames += glob.glob(os.path.join(d, "u2f*.pub")) if public_key_filenames: info( " found %i existing public key%s" % (len(public_key_filenames, engs(public_key_filenames))), *((" - %s" % x) for x in public_key_filenames)) #pick the first directory: conf_dir = osexpand(get_user_conf_dirs()[0]) if not os.path.exists(conf_dir): os.mkdir(conf_dir) from pyu2f.u2f import GetLocalU2FInterface #@UnresolvedImport try: dev = GetLocalU2FInterface() except Exception as e: error("Failed to open local U2F device:", "%s" % (str(e) or type(e))) return 1 info("Please activate your U2F device now to generate a new key") registered_keys = [] challenge = b'01234567890123456789012345678901' #unused rr = dev.Register(APP_ID, challenge, registered_keys) b = rr.registration_data assert b[0] == 5 pubkey = bytes(b[1:66]) khl = b[66] key_handle = bytes(b[67:67 + khl]) #save to files: key_handle_filename = osexpand(key_handle_filenames[0]) f = open(key_handle_filename, "wb") f.write(hexstr(key_handle).encode()) f.close #find a filename we can use for this public key: i = 1 while True: c = "" if i > 1: c = "-%i" public_key_filename = os.path.join(conf_dir, "u2f%s-pub.hex" % c) if not os.path.exists(public_key_filename): break f = open(public_key_filename, "wb") f.write(hexstr(pubkey).encode()) f.close #info("key handle: %s" % csv(hex40(key_handle)), # "saved to file '%s'" % key_handle_filename, # "public key: %s" % csv(hex40(pubkey)), # "saved to file '%s'" % public_key_filename, # ) info( "key handle saved to file:", "'%s'" % key_handle_filename, "public key saved to file:", "'%s'" % public_key_filename, ) return 0