|
| 1 | +# |
| 2 | +# |
| 3 | +# |
| 4 | +# This program is free software; you can redistribute it and/or modify |
| 5 | +# it under the terms of the GNU General Public License as published by |
| 6 | +# the Free Software Foundation; either version 3 of the License, or |
| 7 | +# (at your option) any later version. |
| 8 | +# |
| 9 | +# This program is distributed in the hope that it will be useful, |
| 10 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | +# GNU General Public License for more details. |
| 13 | +# |
| 14 | +# You should have received a copy of the GNU General Public License |
| 15 | +# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 | +# |
| 17 | +# Author: |
| 18 | +# Alberto Ferrer Sánchez (alberefe@gmail.com) |
| 19 | +# |
| 20 | +import json |
| 21 | +import subprocess |
| 22 | +import logging |
| 23 | +import shutil |
| 24 | + |
| 25 | +from .exceptions import ( |
| 26 | + BitwardenCLIError, |
| 27 | + InvalidCredentialsError, |
| 28 | + CredentialNotFoundError, |
| 29 | +) |
| 30 | + |
| 31 | +logger = logging.getLogger(__name__) |
| 32 | + |
| 33 | + |
| 34 | +class BitwardenManager: |
| 35 | + """Retrieve credentials from Bitwarden. |
| 36 | +
|
| 37 | + This class defines functions to log in, retrieve secrets |
| 38 | + and log out of Bitwarden using the Bitwarden CLI. The |
| 39 | + workflow is: |
| 40 | +
|
| 41 | + manager = BitwardenManager(client_id, client_secret, master_password) |
| 42 | + manager.login() |
| 43 | + manager.get_secret("github") |
| 44 | + manager.get_secret("elasticsearch") |
| 45 | + manager.logout() |
| 46 | +
|
| 47 | + The manager logs in using the client_id, client_secret, and |
| 48 | + master_password given as arguments when creating the instance, |
| 49 | + so the object is reusable along the program. |
| 50 | +
|
| 51 | + The path of Bitwarden CLI (bw) is retrieved using shutil. |
| 52 | + """ |
| 53 | + |
| 54 | + def __init__(self, client_id: str, client_secret: str, master_password: str): |
| 55 | + """ |
| 56 | + Creates BitwardenManager object using API key authentication |
| 57 | +
|
| 58 | + :param str client_id: Bitwarden API client ID |
| 59 | + :param str client_secret: Bitwarden API client secret |
| 60 | + :param str master_password: Master password for unlocking the vault |
| 61 | + """ |
| 62 | + # Session key of the bw session |
| 63 | + self.session_key = None |
| 64 | + |
| 65 | + # API credentials |
| 66 | + self.client_id = client_id |
| 67 | + self.client_secret = client_secret |
| 68 | + self.master_password = master_password |
| 69 | + |
| 70 | + # Get the absolute path to the bw executable |
| 71 | + self.bw_path = shutil.which("bw") |
| 72 | + if not self.bw_path: |
| 73 | + raise BitwardenCLIError("Bitwarden CLI (bw) not found in PATH") |
| 74 | + |
| 75 | + # Set up environment variables for consistent execution context |
| 76 | + self.env = { |
| 77 | + "LANG": "C", |
| 78 | + "BW_CLIENTID": client_id, |
| 79 | + "BW_CLIENTSECRET": client_secret, |
| 80 | + } |
| 81 | + |
| 82 | + def login(self) -> str | None: |
| 83 | + """Log into Bitwarden. |
| 84 | +
|
| 85 | + Use the API authentication key to log in and unlock the vault. After it, |
| 86 | + it will obtain a session key that will be used by to access the vault. |
| 87 | +
|
| 88 | + :returns: The session key for the current Bitwarden session. |
| 89 | +
|
| 90 | + :raises InvalidCredentialsError: If invalid credentials are provided |
| 91 | + :raises BitwardenCLIError: If Bitwarden CLI operations fail |
| 92 | + """ |
| 93 | + # Log in using API key |
| 94 | + login_result = subprocess.run( |
| 95 | + [self.bw_path, "login", "--apikey"], |
| 96 | + input=f"{self.client_id}\n{self.client_secret}\n", |
| 97 | + capture_output=True, |
| 98 | + text=True, |
| 99 | + env=self.env, |
| 100 | + ) |
| 101 | + |
| 102 | + if login_result.returncode != 0: |
| 103 | + error_msg = ( |
| 104 | + login_result.stderr.strip() if login_result.stderr else "Unknown error" |
| 105 | + ) |
| 106 | + logger.error("Error logging in with API key: %s", error_msg) |
| 107 | + raise InvalidCredentialsError( |
| 108 | + "Invalid API credentials provided for Bitwarden" |
| 109 | + ) |
| 110 | + |
| 111 | + # After login, we need to unlock the vault to get a session key |
| 112 | + self.session_key = self._unlock_vault() |
| 113 | + |
| 114 | + return self.session_key |
| 115 | + |
| 116 | + def _unlock_vault(self) -> str: |
| 117 | + """Unlock the vault after authentication. |
| 118 | +
|
| 119 | + Executes the Bitwarden unlock command to obtain a session key |
| 120 | + for an already authenticated user but locked vault. |
| 121 | +
|
| 122 | + :returns: Session key for the unlocked vault |
| 123 | + :raises BitwardenCLIError: If unlock operation fails or returns empty session key |
| 124 | + """ |
| 125 | + # this uses the master password to unlock the vault |
| 126 | + unlock_result = subprocess.run( |
| 127 | + [self.bw_path, "unlock", "--raw"], |
| 128 | + input=f"{self.master_password}\n", |
| 129 | + capture_output=True, |
| 130 | + text=True, |
| 131 | + env=self.env, |
| 132 | + ) |
| 133 | + |
| 134 | + if unlock_result.returncode != 0: |
| 135 | + error_msg = ( |
| 136 | + unlock_result.stderr.strip() |
| 137 | + if unlock_result.stderr |
| 138 | + else "Unknown error" |
| 139 | + ) |
| 140 | + logger.error("Error unlocking vault: %s", error_msg) |
| 141 | + raise BitwardenCLIError(f"Failed to unlock vault: {error_msg}") |
| 142 | + |
| 143 | + # the session key is used when retrieving the secrets with get_secret |
| 144 | + session_key = unlock_result.stdout.strip() |
| 145 | + if not session_key: |
| 146 | + raise BitwardenCLIError("Empty session key received from unlock command") |
| 147 | + |
| 148 | + return session_key |
| 149 | + |
| 150 | + def get_secret(self, item_name: str) -> dict: |
| 151 | + """Retrieve an item from the Bitwarden vault. |
| 152 | +
|
| 153 | + Retrieves all the fields stored for an item with the name |
| 154 | + provided as an argument and returns them as a dictionary. |
| 155 | +
|
| 156 | + The returned dictionary includes fields such as: |
| 157 | + - login: username, password, URIs, TOTP |
| 158 | + - fields: custom fields |
| 159 | + - notes: secure notes |
| 160 | + - name, id, and other metadata |
| 161 | +
|
| 162 | + :param str item_name: The name of the item to retrieve |
| 163 | +
|
| 164 | + :returns: Dictionary containing the item data |
| 165 | + :rtype: dict |
| 166 | +
|
| 167 | + :raises CredentialNotFoundError: If the specific credential is not found |
| 168 | + :raises BitwardenCLIError: If Bitwarden CLI operations fail |
| 169 | + """ |
| 170 | + # Pass session key via command line parameter |
| 171 | + result = subprocess.run( |
| 172 | + [self.bw_path, "get", "item", item_name, "--session", self.session_key], |
| 173 | + capture_output=True, |
| 174 | + text=True, |
| 175 | + env=self.env, |
| 176 | + ) |
| 177 | + |
| 178 | + if result.returncode != 0: |
| 179 | + raise CredentialNotFoundError(f"Credential not found: '{item_name}'") |
| 180 | + |
| 181 | + # Parse the JSON response returned in stdout |
| 182 | + try: |
| 183 | + item = json.loads(result.stdout) |
| 184 | + except json.JSONDecodeError as e: |
| 185 | + logger.error("Failed to parse Bitwarden response: %s", str(e)) |
| 186 | + raise BitwardenCLIError(f"Invalid JSON response from Bitwarden: {e}") |
| 187 | + |
| 188 | + return item |
| 189 | + |
| 190 | + def logout(self) -> None: |
| 191 | + """Log out from Bitwarden and invalidate the session. |
| 192 | +
|
| 193 | + This method ends the current session and clears the session key. |
| 194 | + """ |
| 195 | + logger.info("Logging out from Bitwarden") |
| 196 | + |
| 197 | + # Execute logout command |
| 198 | + result = subprocess.run( |
| 199 | + [self.bw_path, "logout"], |
| 200 | + capture_output=True, |
| 201 | + text=True, |
| 202 | + env=self.env, |
| 203 | + ) |
| 204 | + |
| 205 | + if result.returncode != 0: |
| 206 | + error_msg = result.stderr.strip() if result.stderr else "Unknown error" |
| 207 | + logger.error("Error during logout: %s", error_msg) |
| 208 | + |
| 209 | + # Clear session key for security |
| 210 | + self.session_key = None |
| 211 | + |
| 212 | + logger.info("Successfully logged out from Bitwarden") |
0 commit comments