From d6cdcec5de1a47e413eaa783ea9f7b7a3bae11cc Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Wed, 18 Sep 2019 08:14:12 -0500 Subject: [PATCH] bwpass: Use XDG_RUNTIME_DIR if available For additional protection of the Bitwarden session ID file, it will now be stored in the directory specified by the `XDG_RUNTIME_DIR` environment variable. On most systems, this is a tmpfs filesystem owned and only accessible by the current user. --- src/bwpass.py | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/bwpass.py b/src/bwpass.py index fbc922c..af47c38 100644 --- a/src/bwpass.py +++ b/src/bwpass.py @@ -25,6 +25,7 @@ XDG_CACHE_HOME = os.environ.get( 'XDG_CACHE_HOME', os.path.expanduser('~/.cache'), ) +XDG_RUNTIME_DIR = os.environ.get('XDG_RUNTIME_DIR') BITWARDENCLI_APPDATA_DIR = os.environ.get( 'BITWARDENCLI_APPDATA_DIR', @@ -125,6 +126,21 @@ class Vault: with open(self.cache, 'w') as f: json.dump(self.items, f) + @property + def _bw_session_file(self) -> str: + uid = os.getuid() + if XDG_RUNTIME_DIR: + try: + st = os.stat(XDG_RUNTIME_DIR) + except FileNotFoundError: + pass + else: + if st.st_uid == uid: + return os.path.join(XDG_RUNTIME_DIR, '.bw_session') + else: + return os.path.join(XDG_RUNTIME_DIR, f'.bw_session-{uid}') + return os.path.join(tempfile.gettempdir(), f'.bw_session-{uid}') + @classmethod def load(cls) -> 'Vault': self = cls() @@ -172,11 +188,7 @@ class Vault: self.items = json.load(f) def lock(self) -> None: - uid = os.getuid() - fn = os.path.join( - tempfile.gettempdir(), - f'.bw_session-{uid}', - ) + fn = self._bw_session_file try: os.unlink(fn) except FileNotFoundError: @@ -184,11 +196,7 @@ class Vault: self.session_id = None def unlock(self) -> None: - uid = os.getuid() - fn = os.path.join( - tempfile.gettempdir(), - f'.bw_session-{uid}', - ) + fn = self._bw_session_file try: with open(fn) as f: log.debug('Loading session ID from %s', fn)