├── .bumpversion.cfg ├── .coveragerc ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── bitwarden_simple_cli ├── Bitwarden.py ├── CliSimple.py ├── CliSimple_test.py ├── __init__.py ├── __main__.py ├── __version__.py ├── enums │ ├── CipherType.py │ ├── EncryptionType.py │ ├── FieldType.py │ └── __init__.py ├── exceptions │ ├── ManagedException.py │ └── __init__.py ├── models │ ├── __init__.py │ ├── api │ │ ├── FieldApi.py │ │ ├── LoginApi.py │ │ └── __init__.py │ ├── data │ │ ├── CipherData.py │ │ ├── FieldData.py │ │ ├── LoginData.py │ │ └── __init__.py │ ├── domain │ │ ├── Cipher.py │ │ ├── CipherString.py │ │ ├── Cipher_test.py │ │ ├── DecryptParameters.py │ │ ├── DomainBase.py │ │ ├── Field.py │ │ ├── Login.py │ │ ├── LoginUri.py │ │ ├── SymmetricCryptoKey.py │ │ ├── SymmetricCryptoKey_test.py │ │ └── __init__.py │ └── response │ │ ├── BaseResponse.py │ │ ├── BaseResponse_test.py │ │ ├── CipherResponse.py │ │ ├── CipherResponse_test.py │ │ └── __init__.py ├── services │ ├── CipherService.py │ ├── CipherService_test.py │ ├── ContainerService.py │ ├── ContainerService_test.py │ ├── CryptoService.py │ ├── CryptoService_test.py │ ├── SecureStorageService.py │ ├── SecureStorageService_test.py │ ├── StorageService.py │ ├── StorageService_test.py │ ├── Tools.py │ ├── UserService.py │ ├── UserService_test.py │ └── __init__.py └── tests │ ├── __init__.py │ ├── data.json │ └── fixtures_common.py ├── main.py ├── requirements.txt ├── requirements ├── common.txt ├── dev.txt └── prod.txt └── setup.py /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 1.3.1 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:bitwarden_simple_cli/__version__.py] 7 | 8 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | source = 3 | . 4 | 5 | omit = 6 | bitwarden_simple_cli/__main__.py -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | __pycache__/ 3 | /dist 4 | /build 5 | *.egg-info 6 | .coverage 7 | coverage.xml -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: "3.7" 3 | dist: bionic 4 | before_install: pip3 install --upgrade pip && pip3 install -r requirements/dev.txt 5 | install: 6 | - pip3 install bitwarden_simple_cli 7 | - pip3 install codecov 8 | script: pytest --cov-report=xml --cov=bitwarden_simple_cli 9 | deploy: 10 | skip_cleanup: true 11 | provider: pypi 12 | user: mickaelperrin 13 | distributions: "bdist bdist_wheel" 14 | password: 15 | secure: "Vh5Ly3iK8M5MBQ2tgCHBetsA4f7w4I4/oAnMTwr4FZ6UNDjczKoqtgYWt/IsVJSyJJK79gWdhZy8iwoq7tM1gO57Lj1vOJZhibXHPJGqq4R4hbBWtNmjwmMi88d4kd2m1P48ZYyi7gl0JnjdgCUAHHSCczrJ9jEFVzS6x+EY+dYQXrx4p1S3GkMG6gLAMZVyaXmbC1lX0iHME1O3/0UfmwDjaVGURx/r5j+l0XU+7d+uo3iO/gve/Izyc/4joRGVRLRGWu9gKx2mCbVYurawrV2qNGWdpUanFONneB4F8SJwhgsSKHE/be/FzrZw4dOWW2CMIeDZM5Se0X9F1/lvtK6LYttmHanoo/UL62vhl8e49irvVAM/jY5OgG3CKriQMFwoxrLlziZr6XkZmkSzVpULSOI/FyW1t1vt05Gel5OYtL79f43eVHAgLHxk9wggmkPV1B0GFTeciNtKCiadTQDbRDA8qcwxcaC5SGgNcw6VorrFjiFT1YeJ9dXi7Jp9knljIhCVRM87CGIFxNhk+JgH5aZ43+t5rKFbLhr78RmmyC5d/5yR3uhP5iSdmu1rK5B8acMQpyg29ehKLEFhCo6wm24ut026Wpdr3cM1XgZP9a5ORWby1TQQj0v8JmtSKFJ/Vn3ZU/fHbuO6M7rA73MQ0y5hzqLpHCTzzagw540=" 16 | skip_existing: true 17 | on: 18 | branch: master 19 | tags: true 20 | after_success: 21 | - codecov 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bitwarden decrypt CLI 2 | [![Build Status](https://travis-ci.org/mickaelperrin/bitwarden-decrypt-cli.png?branch=master)](https://travis-ci.org/mickaelperrin/bitwarden-decrypt-cli) 3 | [![codecov](https://codecov.io/gh/mickaelperrin/bitwarden-decrypt-cli/branch/master/graph/badge.svg)](https://codecov.io/gh/mickaelperrin/bitwarden-decrypt-cli) 4 | 5 | > This is an _**unofficial**_ port of the Bitwarden NodeJS CLI to Python 6 | > focused on decryption of secrets with increased performance 7 | 8 | ## How to install 9 | 10 | ### Pip 11 | ``` 12 | pip3 install bitwarden-simple-cli 13 | ``` 14 | 15 | ## How to use ? 16 | 17 | This tool do not replace the official NodeJs CLI of Bitwarden. You still need it to perform auth, unlock and sync operations. 18 | 19 | First, ensure that your bitwarden vault in unlocked and that you register the BW_SESSION in your environment. 20 | 21 | ### Get decrypted valued 22 | ``` 23 | bw-simple get [FIELD=password] UUID 24 | ``` 25 | ### List items 26 | ``` 27 | bw-simple list 28 | ``` 29 | 30 | ## Currently supported fields 31 | 32 | The script currently handles the decryption of the following entities and fields: 33 | 34 | - login 35 | - [ custom field name ] 36 | - name 37 | - notes 38 | - password 39 | - uri: retrieve first uri without new line 40 | - uris: retrieve all uris, one per line 41 | - username 42 | - note 43 | - [ custom field name ] 44 | - name 45 | - notes 46 | 47 | It supports decryption of personal and organization ciphers. 48 | 49 | ## Why this project ? 50 | 51 | We use Ansible to manage infrastructures and use a lookup plugin to grab hundred of secrets. Each secret is retrieven 52 | with the native NodeJS CLI in about 0.85s on my computer. When you have hundreds of secrets, that makes long minutes to wait. 53 | 54 | According to https://github.com/bitwarden/cli/issues/67, node looks like to suffer from slow bootstrap. 55 | 56 | This port to Python is aimed to increase secrets lookup performance. First benchmarks spotted that secrets could be 57 | retrieven in around 0.15s with this port. 58 | 59 | ### Benchmark 60 | 61 | #### Original bw cli: 20 requests - 17,21s 62 | ``` 63 | time (for i in {1..20}; do IDS=('5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0' 'e050ece7-2361-4415-860b-aa2a00d9d2bd' '684119e7-3039-45f3-95e3-aa2a00db18f9') FIELDS=('password' 'username'); eval "time bw get ${FIELDS[$((RANDOM % ${#FIELDS[@]}+1))]} ${IDS[$((RANDOM % ${#IDS[@]}+1))]} > /dev/null"; done) 64 | bw get password 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,83s user 0,10s system 118% cpu 0,786 total 65 | bw get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,83s user 0,10s system 118% cpu 0,786 total 66 | bw get password 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,86s user 0,11s system 117% cpu 0,817 total 67 | bw get username e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,87s user 0,11s system 117% cpu 0,832 total 68 | bw get username 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,86s user 0,11s system 119% cpu 0,809 total 69 | bw get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,84s user 0,10s system 119% cpu 0,787 total 70 | bw get username e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,84s user 0,10s system 119% cpu 0,790 total 71 | bw get password 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,85s user 0,10s system 118% cpu 0,807 total 72 | bw get username 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,85s user 0,10s system 117% cpu 0,806 total 73 | bw get username e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,84s user 0,10s system 117% cpu 0,794 total 74 | bw get username 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,84s user 0,10s system 118% cpu 0,796 total 75 | bw get username e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,85s user 0,10s system 118% cpu 0,800 total 76 | bw get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,85s user 0,10s system 118% cpu 0,797 total 77 | bw get password 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,85s user 0,10s system 117% cpu 0,804 total 78 | bw get password 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,86s user 0,10s system 118% cpu 0,810 total 79 | bw get password 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,86s user 0,10s system 118% cpu 0,816 total 80 | bw get password e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,87s user 0,11s system 118% cpu 0,821 total 81 | bw get password 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,85s user 0,10s system 118% cpu 0,806 total 82 | bw get password e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,93s user 0,12s system 117% cpu 0,888 total 83 | bw get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 1,00s user 0,13s system 116% cpu 0,970 total 84 | ( for i in {1..20}; do; IDS=('5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0' ) FIELDS) 17,21s user 2,11s system 118% cpu 16,327 total 85 | ``` 86 | 87 | 88 | #### bw-simple: 20 requests - 2,2s 89 | 90 | ``` 91 | time (for i in {1..20}; do IDS=('5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0' 'e050ece7-2361-4415-860b-aa2a00d9d2bd' '684119e7-3039-45f3-95e3-aa2a00db18f9') FIELDS=('password' 'username'); eval "time bw-simple get ${FIELDS[$((RANDOM % ${#FIELDS[@]}+1))]} ${IDS[$((RANDOM % ${#IDS[@]}+1))]} > /dev/null"; done) 92 | bw-simple get username e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,08s user 0,03s system 84% cpu 0,134 total 93 | bw-simple get password 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,08s user 0,02s system 96% cpu 0,110 total 94 | bw-simple get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,08s user 0,02s system 96% cpu 0,113 total 95 | bw-simple get password e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,09s user 0,03s system 96% cpu 0,116 total 96 | bw-simple get password e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,08s user 0,03s system 95% cpu 0,108 total 97 | bw-simple get password e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,08s user 0,02s system 96% cpu 0,107 total 98 | bw-simple get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,09s user 0,03s system 97% cpu 0,116 total 99 | bw-simple get password 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,09s user 0,03s system 96% cpu 0,122 total 100 | bw-simple get password 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,09s user 0,03s system 95% cpu 0,115 total 101 | bw-simple get username e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,09s user 0,03s system 97% cpu 0,115 total 102 | bw-simple get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,08s user 0,03s system 96% cpu 0,113 total 103 | bw-simple get username e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,09s user 0,03s system 96% cpu 0,118 total 104 | bw-simple get password e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,08s user 0,03s system 95% cpu 0,109 total 105 | bw-simple get password 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,08s user 0,02s system 96% cpu 0,102 total 106 | bw-simple get password e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,08s user 0,02s system 96% cpu 0,102 total 107 | bw-simple get username e050ece7-2361-4415-860b-aa2a00d9d2bd > /dev/null 0,08s user 0,02s system 96% cpu 0,106 total 108 | bw-simple get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,08s user 0,02s system 97% cpu 0,106 total 109 | bw-simple get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,08s user 0,02s system 96% cpu 0,110 total 110 | bw-simple get password 684119e7-3039-45f3-95e3-aa2a00db18f9 > /dev/null 0,09s user 0,03s system 96% cpu 0,115 total 111 | bw-simple get username 5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0 > /dev/null 0,08s user 0,02s system 96% cpu 0,107 total 112 | ( for i in {1..20}; do; IDS=('5bfd3729-7074-46f8-bbe8-aa2a00d8c0f0' ) FIELDS) 1,64s user 0,52s system 95% cpu 2,250 total 113 | ``` 114 | 115 | ## Development 116 | 117 | Development requirements are listed in requirements/dev.txt 118 | 119 | ``` 120 | mkvirtualenv3 bitwarden-simple-cli 121 | workon bitwarden-simple-cli 122 | pip3 install -r requirements/dev.txt 123 | ``` 124 | 125 | ## Testing 126 | 127 | Testing is done through `pytest`. A sample database unlocked with `BW_SESSION` are provided. 128 | 129 | ## License 130 | 131 | GPLv3 132 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/Bitwarden.py: -------------------------------------------------------------------------------- 1 | from os import environ 2 | from sys import exit, stdout, stderr 3 | from bitwarden_simple_cli.services.ContainerService import ContainerService 4 | from bitwarden_simple_cli.services.CryptoService import CryptoService 5 | from bitwarden_simple_cli.services.SecureStorageService import SecureStorageService 6 | from bitwarden_simple_cli.services.StorageService import StorageService 7 | from bitwarden_simple_cli.services.UserService import UserService 8 | from bitwarden_simple_cli.services.CipherService import CipherService 9 | from bitwarden_simple_cli.exceptions.ManagedException import ManagedException 10 | 11 | 12 | class Bitwarden: 13 | containerService: ContainerService 14 | cryptoService: CryptoService 15 | secureStorageService: SecureStorageService 16 | storageService: StorageService 17 | 18 | def __init__(self): 19 | self.storageService = StorageService() 20 | self.cryptoService = CryptoService(self.storageService) 21 | self.secureStorageService = SecureStorageService(self.storageService, self.cryptoService) 22 | self.userService = UserService(self.storageService) 23 | self.cipherService = CipherService(self.storageService, self.userService) 24 | self.containerService = ContainerService() 25 | self.containerService.add_service(self.cryptoService) 26 | self.containerService.add_service(self.secureStorageService) 27 | 28 | def _exit_if_no_session(self): 29 | if not environ.get('BW_SESSION'): 30 | print('Environement variable BW_SESSION is not set.') 31 | exit(1) 32 | if not self.cryptoService.has_key(): 33 | print('Vault is locked.') 34 | exit(1) 35 | 36 | def get(self, uuid, field): 37 | self._exit_if_no_session() 38 | cipher = self.cipherService.get(uuid) 39 | if cipher is None: 40 | raise ManagedException('Unable to find entry with id: ' + uuid) 41 | return cipher.decrypt_field(field) 42 | 43 | def list(self): 44 | self._exit_if_no_session() 45 | ciphers = self.storageService.list_ciphers(self.userService.get_user_id()) 46 | return ciphers 47 | 48 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/CliSimple.py: -------------------------------------------------------------------------------- 1 | from .__version__ import __version__ 2 | from sys import exit 3 | from bitwarden_simple_cli.Bitwarden import Bitwarden 4 | from bitwarden_simple_cli.exceptions.ManagedException import ManagedException 5 | from uuid import UUID 6 | 7 | 8 | def is_uuid(uuid_string, version=4): 9 | try: 10 | uid = UUID(uuid_string, version=version) 11 | return uid.hex == uuid_string.replace('-', '') 12 | except ValueError: 13 | return False 14 | 15 | 16 | class CliSimple: 17 | 18 | action: str 19 | field: str 20 | script_name: str 21 | uuid: str 22 | 23 | def __init__(self, script_name, action='version', field='password', uuid=None): 24 | self.field = field 25 | self.uuid = uuid 26 | if uuid is None and is_uuid(self.field): 27 | self.field = 'password' 28 | self.uuid = field 29 | self.action = action 30 | self.script_name = script_name 31 | 32 | def run(self): 33 | if self.action == 'get': 34 | if self.uuid is None: 35 | print('Error: UUID is required to get secret') 36 | print(self.usage()) 37 | exit(1) 38 | return self.get(self.uuid, self.field) 39 | elif self.action == 'list': 40 | return self.list() 41 | else: 42 | return self.version() 43 | 44 | @staticmethod 45 | def usage(action='get'): 46 | if action == 'get': 47 | print('Usage: get UUID [field]') 48 | 49 | @staticmethod 50 | def get(uuid, field): 51 | try: 52 | app = Bitwarden() 53 | decrypted_value = app.get(uuid, field) 54 | if type(decrypted_value).__name__ == 'bytes': 55 | print(str(decrypted_value, 'utf-8'), end='') 56 | return decrypted_value 57 | elif type(decrypted_value).__name__ == 'list': 58 | for item in decrypted_value: 59 | print(str(item, 'utf-8')) 60 | return decrypted_value 61 | else: 62 | print(decrypted_value, file=stderr) 63 | except ManagedException as e: 64 | exit(e.args[0]) 65 | 66 | @staticmethod 67 | def list(): 68 | app = Bitwarden() 69 | ciphers = app.list() 70 | for cipher in ciphers: 71 | print(cipher['id'] + ' ' + str(cipher['name'].decrypt(cipher['org_id']), 'utf-8')) 72 | 73 | 74 | @staticmethod 75 | def version(): 76 | print('Version: ' + __version__) 77 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/CliSimple_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from bitwarden_simple_cli.CliSimple import CliSimple 3 | from bitwarden_simple_cli.__version__ import __version__ 4 | from bitwarden_simple_cli.tests.fixtures_common import common_data, bw_session, no_bw_session 5 | from bitwarden_simple_cli.exceptions.ManagedException import ManagedException 6 | 7 | nl = common_data("nl") 8 | 9 | @pytest.fixture 10 | def cli_version(): 11 | return CliSimple('script', 'version') 12 | 13 | 14 | @pytest.fixture 15 | def cli_empty(): 16 | return CliSimple('script') 17 | 18 | 19 | @pytest.fixture 20 | def cli_get_empty(): 21 | return CliSimple('script', 'get') 22 | 23 | 24 | @pytest.fixture 25 | def cli_get_uuid(): 26 | return CliSimple('script', 'get', common_data('uuid_login_personal')) 27 | 28 | 29 | @pytest.fixture 30 | def cli_get_uuid_username(): 31 | return CliSimple('script', 'get', 'username', common_data('uuid_login_personal')) 32 | 33 | 34 | def test_version(cli_version, capsys): 35 | cli_version.run() 36 | std = capsys.readouterr() 37 | assert std.out == 'Version: ' + __version__ + nl 38 | 39 | 40 | def test_get_empty(cli_get_empty, capsys): 41 | with pytest.raises(SystemExit) as exit_code: 42 | cli_get_empty.run() 43 | std = capsys.readouterr() 44 | assert exit_code.type == SystemExit 45 | assert exit_code.value.code == 1 46 | assert std.out.find('Error:') != -1 47 | assert std.out.find('Usage:') != -1 48 | 49 | 50 | @pytest.mark.usefixtures("no_bw_session") 51 | def test_get_uuid(cli_get_uuid, capsys, no_bw_session): 52 | with pytest.raises(SystemExit) as exit_code: 53 | cli_get_uuid.run() 54 | std = capsys.readouterr() 55 | assert std.out.find('BW_SESSION is not set') != -1 56 | assert exit_code.type == SystemExit 57 | assert exit_code.value.code == 1 58 | 59 | 60 | @pytest.mark.usefixtures("bw_session") 61 | def test_get_return_value(cli_get_uuid, capsys, bw_session): 62 | return_value = cli_get_uuid.run() 63 | assert return_value == b'login_p_password' 64 | 65 | 66 | @pytest.mark.usefixtures("bw_session") 67 | def test_get_uuid_without_field(cli_get_uuid, capsys, bw_session): 68 | cli_get_uuid.run() 69 | std = capsys.readouterr() 70 | assert std.out == 'login_p_password' 71 | 72 | 73 | @pytest.mark.usefixtures("bw_session") 74 | def test_get_login_organization_password(cli_get_uuid_username, capsys): 75 | CliSimple('script', 'get', 'password', common_data('uuid_login_organization')).run() 76 | std = capsys.readouterr() 77 | assert std.out == 'acme_login1_password' 78 | 79 | 80 | @pytest.mark.usefixtures("bw_session") 81 | def test_get_login_personal_username(cli_get_uuid_username, capsys): 82 | cli_get_uuid_username.run() 83 | std = capsys.readouterr() 84 | assert std.out == 'login_p_username' 85 | 86 | 87 | @pytest.mark.usefixtures("bw_session") 88 | def test_get_login_organization_username(cli_get_uuid_username, capsys): 89 | CliSimple('script', 'get', 'username', common_data('uuid_login_organization')).run() 90 | std = capsys.readouterr() 91 | assert std.out == 'acme_login1' 92 | 93 | 94 | @pytest.mark.usefixtures("bw_session") 95 | def test_get_login_personal_uri(capsys): 96 | CliSimple('script', 'get', 'uri', common_data('uuid_login_personal')).run() 97 | std = capsys.readouterr() 98 | assert std.out == 'login_p_uri1' 99 | 100 | 101 | @pytest.mark.usefixtures("bw_session") 102 | def test_get_login_organization_uri(cli_get_uuid_username, capsys): 103 | CliSimple('script', 'get', 'uri', common_data('uuid_login_organization')).run() 104 | std = capsys.readouterr() 105 | assert std.out == 'acme_login1_url1' 106 | 107 | 108 | @pytest.mark.usefixtures("bw_session") 109 | def test_get_login_personal_uris(capsys): 110 | CliSimple('script', 'get', 'uris', common_data('uuid_login_personal')).run() 111 | std = capsys.readouterr() 112 | assert std.out == 'login_p_uri1\nlogin_p_uri2\n' 113 | 114 | 115 | @pytest.mark.usefixtures("bw_session") 116 | def test_get_login_organization_uris(cli_get_uuid_username, capsys): 117 | CliSimple('script', 'get', 'uris', common_data('uuid_login_organization')).run() 118 | std = capsys.readouterr() 119 | assert std.out == 'acme_login1_url1\nacme_login2_url2\n' 120 | 121 | 122 | @pytest.mark.usefixtures("bw_session") 123 | def test_get_login_personal_name(capsys): 124 | CliSimple('script', 'get', 'name', common_data('uuid_login_personal')).run() 125 | std = capsys.readouterr() 126 | assert std.out == 'login personnal' 127 | 128 | 129 | @pytest.mark.usefixtures("bw_session") 130 | def test_get_login_organization_name(cli_get_uuid_username, capsys): 131 | CliSimple('script', 'get', 'name', common_data('uuid_login_organization')).run() 132 | std = capsys.readouterr() 133 | assert std.out == 'acme login 1' 134 | 135 | 136 | @pytest.mark.usefixtures("bw_session") 137 | def test_get_login_personal_notes(capsys): 138 | CliSimple('script', 'get', 'notes', common_data('uuid_login_personal')).run() 139 | std = capsys.readouterr() 140 | assert std.out == 'login_p_notes' 141 | 142 | 143 | @pytest.mark.usefixtures("bw_session") 144 | def test_get_login_organization_notes(cli_get_uuid_username, capsys): 145 | CliSimple('script', 'get', 'notes', common_data('uuid_login_organization')).run() 146 | std = capsys.readouterr() 147 | assert std.out == 'acme_login1_note' 148 | 149 | 150 | @pytest.mark.usefixtures("bw_session") 151 | def test_get_note_personal_notes(capsys): 152 | CliSimple('script', 'get', 'notes', common_data('uuid_note_personal')).run() 153 | std = capsys.readouterr() 154 | assert std.out == 'note_p_content' 155 | 156 | 157 | @pytest.mark.usefixtures("bw_session") 158 | def test_get_note_personal_name(capsys): 159 | CliSimple('script', 'get', 'name', common_data('uuid_note_personal')).run() 160 | std = capsys.readouterr() 161 | assert std.out == 'note personal' 162 | 163 | 164 | @pytest.mark.usefixtures("bw_session") 165 | def test_get_login_organization_custom_field_text(cli_get_uuid_username, capsys): 166 | CliSimple('script', 'get', 'acme_login1_customfield_text1', common_data('uuid_login_organization')).run() 167 | std = capsys.readouterr() 168 | assert std.out == 'acme_login1_customfield_text1_value' 169 | 170 | 171 | @pytest.mark.usefixtures("bw_session") 172 | def test_get_login_personal_custom_field_text(cli_get_uuid_username, capsys): 173 | CliSimple('script', 'get', 'login_p_custom_text', common_data('uuid_login_personal')).run() 174 | std = capsys.readouterr() 175 | assert std.out == 'login_p_custom_text_value' 176 | 177 | 178 | @pytest.mark.usefixtures("bw_session") 179 | def test_get_login_personal_custom_field_hidden(cli_get_uuid_username, capsys): 180 | CliSimple('script', 'get', 'login_p_custom_hidden', common_data('uuid_login_personal')).run() 181 | std = capsys.readouterr() 182 | assert std.out == 'login_p_custom_hidden_value' 183 | 184 | 185 | @pytest.mark.usefixtures("bw_session") 186 | def test_get_login_personal_custom_field_unchecked(cli_get_uuid_username, capsys): 187 | CliSimple('script', 'get', 'login_p_custom_unchecked', common_data('uuid_login_personal')).run() 188 | std = capsys.readouterr() 189 | assert std.out == 'false' 190 | 191 | 192 | @pytest.mark.usefixtures("bw_session") 193 | def test_get_note_personal_customfield(capsys): 194 | CliSimple('script', 'get', 'note_p_custom_field_text', common_data('uuid_note_personal')).run() 195 | std = capsys.readouterr() 196 | assert std.out == 'note_p_custom_field_text_value' 197 | 198 | 199 | @pytest.mark.usefixtures("bw_session") 200 | def test_list(capsys): 201 | CliSimple('script', 'list').run() 202 | std = capsys.readouterr() 203 | assert std.out == \ 204 | "fe6e74aa-a099-4cc1-ae8e-aa3000d02c14 acme login 1\n\ 205 | fd8870cc-3659-40aa-9492-aa3000cedbb3 login personnal\n\ 206 | 450cbad2-580b-4523-bce8-aa3000cf641a note personal\n" 207 | 208 | 209 | @pytest.mark.usefixtures("bw_session") 210 | def test_get_wrong_uuid(): 211 | with pytest.raises(SystemExit) as e: 212 | CliSimple('script', 'get', 'name', 'wrong-uuid').run() 213 | assert e.type == SystemExit 214 | assert e.value.code == 'Unable to find entry with id: wrong-uuid' 215 | 216 | 217 | @pytest.mark.usefixtures("bw_session") 218 | def test_get_wrong_field(): 219 | with pytest.raises(SystemExit) as e: 220 | CliSimple('script', 'get', 'unexisting', common_data('uuid_note_personal')).run() 221 | assert e.type == SystemExit 222 | assert e.value.code == 'Unable to find field unexisting for entry with id: ' + common_data('uuid_note_personal') 223 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/__init__.py: -------------------------------------------------------------------------------- 1 | from .CliSimple import CliSimple -------------------------------------------------------------------------------- /bitwarden_simple_cli/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import sys 3 | from bitwarden_simple_cli.CliSimple import CliSimple 4 | 5 | 6 | def start(): 7 | cli = CliSimple(*sys.argv) 8 | cli.run() 9 | 10 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/__version__.py: -------------------------------------------------------------------------------- 1 | __version__ = "1.3.1" -------------------------------------------------------------------------------- /bitwarden_simple_cli/enums/CipherType.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class CipherType(Enum): 5 | Login = 1 6 | SecureNote = 2 7 | Card = 3 8 | Identity = 4 9 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/enums/EncryptionType.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class EncryptionType(Enum): 5 | AesCbc256_B64 = 0 6 | AesCbc128_HmacSha256_B64 = 1 7 | AesCbc256_HmacSha256_B64 = 2 8 | Rsa2048_OaepSha256_B64 = 3 9 | Rsa2048_OaepSha1_B64 = 4 10 | Rsa2048_OaepSha256_HmacSha256_B64 = 5 11 | Rsa2048_OaepSha1_HmacSha256_B64 = 6 12 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/enums/FieldType.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class FieldType(Enum): 5 | Text = 0 6 | Hidden = 1 7 | Boolean = 2 8 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/enums/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mickaelperrin/bitwarden-decrypt-cli/43bb50ed80fe2159294bc7e191ee8756d6db7070/bitwarden_simple_cli/enums/__init__.py -------------------------------------------------------------------------------- /bitwarden_simple_cli/exceptions/ManagedException.py: -------------------------------------------------------------------------------- 1 | 2 | class ManagedException(Exception): 3 | def __init__(self, *args, **kwargs): 4 | Exception.__init__(self, *args, **kwargs) 5 | 6 | 7 | class ProperExit(Exception): 8 | def __init__(self, *args, message='', **kwargs) : 9 | Exception.__init__(self, *args, **kwargs) -------------------------------------------------------------------------------- /bitwarden_simple_cli/exceptions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mickaelperrin/bitwarden-decrypt-cli/43bb50ed80fe2159294bc7e191ee8756d6db7070/bitwarden_simple_cli/exceptions/__init__.py -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mickaelperrin/bitwarden-decrypt-cli/43bb50ed80fe2159294bc7e191ee8756d6db7070/bitwarden_simple_cli/models/__init__.py -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/api/FieldApi.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.enums.FieldType import FieldType 2 | from bitwarden_simple_cli.models.response.BaseResponse import BaseResponse 3 | 4 | 5 | class FieldApi(BaseResponse): 6 | name: str 7 | value: str 8 | type: FieldType 9 | 10 | def __init__(self, data): 11 | super().__init__(data) 12 | if data is None: 13 | return 14 | self.type = self.get_response_property_name('Type') 15 | self.name = self.get_response_property_name('Name') 16 | self.value = self.get_response_property_name('Value') 17 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/api/LoginApi.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.models.response.BaseResponse import BaseResponse 2 | 3 | 4 | class LoginApi(BaseResponse): 5 | username: str 6 | password: str 7 | 8 | def __init__(self, data): 9 | super().__init__(data) 10 | if data is None: 11 | return 12 | self.username = self.get_response_property_name('Username') 13 | self.password = self.get_response_property_name('Password') 14 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mickaelperrin/bitwarden-decrypt-cli/43bb50ed80fe2159294bc7e191ee8756d6db7070/bitwarden_simple_cli/models/api/__init__.py -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/data/CipherData.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.enums.CipherType import CipherType 2 | from bitwarden_simple_cli.models.data.FieldData import FieldData 3 | from bitwarden_simple_cli.models.data.LoginData import LoginData 4 | from bitwarden_simple_cli.models.response.CipherResponse import CipherResponse 5 | 6 | 7 | class CipherData: 8 | collectionIds: [] 9 | fields: [] 10 | id: str 11 | login: LoginData 12 | organizationId: str 13 | type: CipherType 14 | userId: str 15 | 16 | def __init(self, response: CipherResponse, user_id: str, collection_ids: []): 17 | if response is None: 18 | return 19 | 20 | self.id = response.id 21 | self.organizationId = response.organizationId 22 | self.type = CipherType(int(response.type)) 23 | self.userId = user_id 24 | 25 | if collection_ids: 26 | self.collectionIds = collection_ids 27 | else: 28 | self.collectionIds = response.collectionsIds 29 | 30 | if self.type == CipherType.Login: 31 | self.login = LoginData(response.login) 32 | 33 | if response.fields: 34 | self.fields = [] 35 | for field in response.fields: 36 | self.fields.append(FieldData(field)) 37 | 38 | def __getattr__(self, item): 39 | return self.item 40 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/data/FieldData.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.enums.FieldType import FieldType 2 | from bitwarden_simple_cli.models.api.FieldApi import FieldApi 3 | 4 | 5 | class FieldData: 6 | type: FieldType 7 | name: str 8 | value: str 9 | 10 | def __init__(self, response: FieldApi): 11 | if response is None: 12 | return 13 | 14 | self.type = response.type 15 | self.name = response.name 16 | self.value = response.value 17 | 18 | def __getattr__(self, item): 19 | return self.item 20 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/data/LoginData.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.models.api.LoginApi import LoginApi 2 | 3 | 4 | class LoginData: 5 | username: str 6 | password: str 7 | 8 | def __init__(self, data: LoginApi): 9 | if data is None: 10 | return 11 | 12 | self.username = data.username 13 | self.password = data.password 14 | 15 | def __getattr__(self, item): 16 | return self.item 17 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mickaelperrin/bitwarden-decrypt-cli/43bb50ed80fe2159294bc7e191ee8756d6db7070/bitwarden_simple_cli/models/data/__init__.py -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/Cipher.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.models.data.CipherData import CipherData 2 | from bitwarden_simple_cli.models.domain.DomainBase import Domain 3 | from bitwarden_simple_cli.models.domain.Field import Field 4 | from bitwarden_simple_cli.enums.CipherType import CipherType 5 | from bitwarden_simple_cli.models.domain.Login import Login 6 | from bitwarden_simple_cli.exceptions.ManagedException import ManagedException 7 | 8 | 9 | class Cipher(Domain): 10 | id = None 11 | fields = None 12 | login = None 13 | folderId = None 14 | name = None 15 | response = None 16 | type: CipherType 17 | userId = None 18 | organizationId = None 19 | 20 | def __init__(self, obj: CipherData, already_encrypted=False, local_data=None): 21 | super().__init__() 22 | if obj is None: 23 | return 24 | self.build_domain_model(self, obj, 25 | { 26 | 'id': None, 27 | 'userId': None, 28 | 'organizationId': None, 29 | 'folderId': None, 30 | 'name': None, 31 | 'notes': None 32 | }, already_encrypted, 33 | [ 34 | 'id', 35 | 'userId', 36 | 'organizationId', 37 | 'folderId' 38 | ]) 39 | 40 | self.type = CipherType(int(obj['type'])) 41 | 42 | if self.type == CipherType.Login: 43 | self.login = Login(obj['login'], already_encrypted) 44 | 45 | if obj.get('fields'): 46 | self.fields = [] 47 | for field in obj['fields']: 48 | self.fields.append(Field(field, already_encrypted)) 49 | 50 | def decrypt_field(self, field): 51 | if field in ['name', 'notes']: 52 | return self.__getattribute__(field).decrypt(self.organizationId) 53 | elif field in ['username', 'password']: 54 | return self.login.decrypt_field(field, self.organizationId) 55 | elif field == 'uri': 56 | return self.login.decrypt_uri(self.organizationId, 1) 57 | elif field == 'uris': 58 | return [self.login.decrypt_uri(self.organizationId, i) for i in range(1, len(self.login.uris)+1)] 59 | elif len(self.fields) > 0: 60 | # try custom fields 61 | for custom_field in self.fields: 62 | if str(custom_field.name.decrypt(self.organizationId), 'utf-8') == field: 63 | return custom_field.value.decrypt(self.organizationId) 64 | raise ManagedException('Unable to find field %s for entry with id: %s' % (field, self.id)) 65 | 66 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/CipherString.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.enums.EncryptionType import EncryptionType 2 | from bitwarden_simple_cli.services.Tools import T 3 | import bitwarden_simple_cli.services.ContainerService as ContainerService 4 | 5 | 6 | class CipherString: 7 | 8 | encryptedString: str = None 9 | encryptionType: EncryptionType = None 10 | decryptedValue: str = None 11 | data: str = None 12 | ic: str = None 13 | mac: str = None 14 | 15 | def __init__(self, encrypted_string_or_type: str, data: str = None, iv: str = None, mac: str = None): 16 | if data: 17 | enc_type = EncryptionType(encrypted_string_or_type) 18 | self.encryptedString = encrypted_string_or_type + '.' + data 19 | 20 | if iv: 21 | self.encryptedString += '|' + iv 22 | 23 | if mac: 24 | self.encryptedString += '|' + mac 25 | 26 | self.encryptionType = enc_type 27 | self.data = data 28 | self.iv = iv 29 | self.mac = mac 30 | return 31 | 32 | self.encryptedString = str(encrypted_string_or_type) 33 | if self.encryptedString is None: 34 | return 35 | 36 | header_pieces = self.encryptedString.split('.') 37 | if len(header_pieces) == 2: 38 | try: 39 | self.encryptionType = EncryptionType(int(header_pieces[0])) 40 | enc_pieces = header_pieces[1].split('|') 41 | except Exception as e: 42 | T.error(e) 43 | return 44 | else: 45 | enc_pieces = self.encryptedString.split('|') 46 | self.encryptionType = EncryptionType.AesCbc128_HmacSha256_B64 \ 47 | if len(enc_pieces) == 3 else EncryptionType.AesCbc256_B64 48 | 49 | if self.encryptionType == EncryptionType.AesCbc128_HmacSha256_B64 \ 50 | or self.encryptionType == EncryptionType.AesCbc256_HmacSha256_B64: 51 | if len(enc_pieces) != 3: 52 | return 53 | self.iv = enc_pieces[0] 54 | self.data = enc_pieces[1] 55 | self.mac = enc_pieces[2] 56 | elif self.encryptionType == EncryptionType.AesCbc256_B64: 57 | if len(enc_pieces) != 2: 58 | return 59 | self.iv = enc_pieces[0] 60 | self.data = enc_pieces[1] 61 | elif self.encryptionType == EncryptionType.Rsa2048_OaepSha256_B64 \ 62 | or self.encryptionType == EncryptionType.Rsa2048_OaepSha1_B64: 63 | if len(enc_pieces) != 1: 64 | return 65 | self.data = enc_pieces[0] 66 | else: 67 | return 68 | 69 | def decrypt(self, org_id): 70 | if self.decryptedValue: 71 | return self.decryptedValue 72 | 73 | cypto_service = ContainerService.ContainerService().get_crypto_service() 74 | if not cypto_service: 75 | raise Exception('Container service not initialized') 76 | 77 | try: 78 | org_key = cypto_service.get_org_key(org_id) 79 | self.decryptedValue = cypto_service.decrypt_to_utf8(self, org_key) 80 | except Exception as e: 81 | T.error(e) 82 | self.decryptedValue = '[error: cannot decrypt]' 83 | return self.decryptedValue 84 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/Cipher_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from bitwarden_simple_cli.models.domain.Cipher import Cipher 3 | from bitwarden_simple_cli.services.StorageService import StorageService 4 | from bitwarden_simple_cli.tests.fixtures_common import common_data, storage_service 5 | from bitwarden_simple_cli.services.CipherService import Keys 6 | from bitwarden_simple_cli.models.domain.Login import Login 7 | from bitwarden_simple_cli.enums.CipherType import CipherType 8 | 9 | 10 | @pytest.fixture() 11 | def cipher_login_personal(storage_service: StorageService): 12 | cipher_response = storage_service.get(Keys['ciphersPrefix'] + common_data('user_id'))\ 13 | [common_data('uuid_login_personal')] 14 | return Cipher(cipher_response) 15 | 16 | 17 | def test_cipher_login_personal(cipher_login_personal: Cipher): 18 | assert cipher_login_personal.id == 'fd8870cc-3659-40aa-9492-aa3000cedbb3' 19 | assert cipher_login_personal.organizationId is None 20 | assert cipher_login_personal.type == CipherType.Login 21 | assert isinstance(cipher_login_personal.login, Login) 22 | assert type(cipher_login_personal.fields).__name__ == 'list' 23 | assert len(cipher_login_personal.fields) == 4 24 | #TODO: cipherString tests 25 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/DecryptParameters.py: -------------------------------------------------------------------------------- 1 | class DecryptParameters: 2 | encKey = None 3 | data = None 4 | iv = None 5 | macKey = None 6 | mac = None 7 | macData = None 8 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/DomainBase.py: -------------------------------------------------------------------------------- 1 | import bitwarden_simple_cli.models.domain.CipherString as CipherString 2 | 3 | 4 | class Domain: 5 | 6 | def __setitem__(self, item, value): 7 | setattr(self, item, value) 8 | 9 | @staticmethod 10 | def build_domain_model(domain, data_obj, mapping, already_encrypted, not_enc_list): 11 | for prop in mapping: 12 | if prop not in data_obj: 13 | continue 14 | obj_prop = data_obj[mapping[prop] or prop] 15 | if already_encrypted or prop in not_enc_list: 16 | domain[prop] = obj_prop if obj_prop else None 17 | else: 18 | domain[prop] = CipherString.CipherString(obj_prop) if obj_prop else None 19 | 20 | def __getitem__(self, item): 21 | return getattr(self, item) 22 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/Field.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.models.domain.CipherString import CipherString 2 | from bitwarden_simple_cli.models.domain.DomainBase import Domain 3 | from bitwarden_simple_cli.models.data.FieldData import FieldData 4 | from bitwarden_simple_cli.enums.FieldType import FieldType 5 | 6 | 7 | class Field(Domain): 8 | 9 | name: CipherString 10 | value: CipherString 11 | type: FieldType 12 | 13 | def __init__(self, obj: FieldData, already_encrypted=False): 14 | super().__init__() 15 | if obj is None: 16 | return 17 | self.type = FieldType(int(obj['type'])) 18 | self.build_domain_model(self, obj, { 19 | 'name': None, 20 | 'value': None, 21 | }, already_encrypted, []) 22 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/Login.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.models.domain.DomainBase import Domain 2 | from bitwarden_simple_cli.models.domain.CipherString import CipherString 3 | from bitwarden_simple_cli.models.data.LoginData import LoginData 4 | from bitwarden_simple_cli.models.domain.LoginUri import LoginUri 5 | 6 | 7 | class Login(Domain): 8 | username: CipherString 9 | password: CipherString 10 | uris: [] = None 11 | 12 | def __init__(self, obj: LoginData, already_encrypted=False): 13 | super().__init__() 14 | if obj is None: 15 | return 16 | 17 | self.build_domain_model(self, obj, 18 | { 19 | 'username': None, 20 | 'password': None 21 | }, already_encrypted, []) 22 | 23 | if obj.get('uris'): 24 | self.uris = [] 25 | for uri in obj['uris']: 26 | self.uris.append(LoginUri(uri, already_encrypted)) 27 | 28 | def decrypt_field(self, field, org_id): 29 | return self[field].decrypt(org_id) 30 | 31 | def decrypt_uri(self, org_id, i=1): 32 | # Only process first URI at the moment 33 | return self.uris[i-1].decrypt(org_id) 34 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/LoginUri.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.models.domain.DomainBase import Domain 2 | from bitwarden_simple_cli.models.domain.CipherString import CipherString 3 | from bitwarden_simple_cli.models.data.LoginData import LoginData 4 | 5 | 6 | class LoginUri(Domain): 7 | uri: CipherString 8 | 9 | def __init__(self, obj: LoginData, already_encrypted: bool = False): 10 | super() 11 | if obj is None: 12 | return 13 | self.build_domain_model(self, obj, 14 | { 15 | 'uri': None, 16 | }, 17 | already_encrypted, 18 | []) 19 | 20 | def decrypt(self, org_id: str): 21 | return self.uri.decrypt(org_id) 22 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/SymmetricCryptoKey.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.enums.EncryptionType import EncryptionType 2 | from base64 import b64encode 3 | 4 | 5 | class SymmetricCryptoKey: 6 | key = None 7 | encKey = None 8 | macKey = None 9 | encType = None 10 | 11 | keyB64 = None 12 | encKeyB64 = None 13 | macKeyB64 = None 14 | 15 | meta = None 16 | 17 | def __init__(self, key, enc_type=None): 18 | if not key: 19 | raise Exception('Must provide ke') 20 | 21 | if enc_type is None: 22 | if len(key) == 32: 23 | enc_type = EncryptionType.AesCbc256_B64 24 | elif len(key) == 64: 25 | enc_type = EncryptionType.AesCbc256_HmacSha256_B64 26 | else: 27 | raise Exception('Unable to determine encType.') 28 | 29 | self.key = key 30 | self.encType = enc_type 31 | 32 | if enc_type == EncryptionType.AesCbc256_B64 and len(key) == 32: 33 | self.encKey = key 34 | self.macKey = None 35 | elif enc_type == EncryptionType.AesCbc128_HmacSha256_B64 and len(key) == 32: 36 | self.encKey = key[0:16] 37 | self.macKey = key[16:32] 38 | elif enc_type == EncryptionType.AesCbc256_HmacSha256_B64 and len(key) == 64: 39 | self.encKey = key[0:32] 40 | self.macKey = key[32:64] 41 | else: 42 | raise Exception('Unsupported encType/key length.') 43 | 44 | if self.key: 45 | self.keyB64 = b64encode(self.key) 46 | if self.encKey: 47 | self.encKeyB64 = b64encode(self.encKey) 48 | if self.macKey: 49 | self.macKeyB64 = b64encode(self.macKey) 50 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/SymmetricCryptoKey_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from bitwarden_simple_cli.models.domain.SymmetricCryptoKey import SymmetricCryptoKey 3 | from bitwarden_simple_cli.tests.fixtures_common import common_data 4 | from base64 import b64decode, b64encode 5 | 6 | 7 | def test_symmetric_crypto_key_aes_cbc_256_b64(): 8 | key = b64decode(common_data('protected_key_decoded')) 9 | sck = SymmetricCryptoKey(key) 10 | assert sck.encType.value == 0 11 | assert sck.encKey == key 12 | assert sck.macKey is None 13 | 14 | 15 | def test_symmetric_crypto_key_aes_cbc_256_hmac_sha_256_b64(): 16 | key = b64decode(common_data('BW_SESSION')) 17 | sck = SymmetricCryptoKey(key) 18 | assert sck.encType.value == 2 19 | assert sck.encKeyB64 == b'Tyy0rDgzvA/jgHsqUtKIgNnAWaRtHKZoSs6pa10qWQc=' 20 | assert sck. macKeyB64 == b'9EJhbXdv8Z/EzScvBbtpz0TVQ6Z95O7buPVtaUFVPGY=' -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/domain/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mickaelperrin/bitwarden-decrypt-cli/43bb50ed80fe2159294bc7e191ee8756d6db7070/bitwarden_simple_cli/models/domain/__init__.py -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/response/BaseResponse.py: -------------------------------------------------------------------------------- 1 | class BaseResponse: 2 | response = None 3 | 4 | def __init__(self, response): 5 | self.response = response 6 | 7 | def get_response_property_name(self, property_name, response=None, exact_name=False): 8 | if property_name is None or property_name == '': 9 | raise Exception('propertyName must not be null/empty.') 10 | 11 | if response is None and self.response is not None: 12 | response = self.response 13 | 14 | if response is None: 15 | return None 16 | 17 | if not exact_name and property_name not in response: 18 | if property_name[0] == property_name[0].upper(): 19 | other_case_property_name = property_name[0].lower() 20 | else: 21 | other_case_property_name = property_name[0].upper() 22 | if len(property_name) > 1: 23 | other_case_property_name += property_name[1:] 24 | 25 | property_name = other_case_property_name 26 | if property_name not in response: 27 | property_name = property_name.lower() 28 | if property_name not in response: 29 | property_name = property_name.upper() 30 | return response.get(property_name) 31 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/response/BaseResponse_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from bitwarden_simple_cli.models.response.BaseResponse import BaseResponse 3 | from bitwarden_simple_cli.tests.fixtures_common import common_data 4 | 5 | 6 | @pytest.fixture() 7 | def base_response(): 8 | return BaseResponse(common_data('cipher_response')) 9 | 10 | 11 | def test_base_response_get_response_property_name(base_response: BaseResponse): 12 | uuid = 'fd8870cc-3659-40aa-9492-aa3000cedbb3' 13 | assert base_response.get_response_property_name('userId') == common_data('user_id') 14 | assert base_response.get_response_property_name('UserId') == common_data('user_id') 15 | assert base_response.get_response_property_name('Id') == uuid 16 | assert base_response.get_response_property_name('id') == uuid 17 | assert base_response.get_response_property_name('ID') == uuid 18 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/response/CipherResponse.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.models.api.LoginApi import LoginApi 2 | from bitwarden_simple_cli.models.api.FieldApi import FieldApi 3 | from bitwarden_simple_cli.models.response.BaseResponse import BaseResponse 4 | 5 | 6 | class CipherResponse(BaseResponse): 7 | collectionsIds = None 8 | id = None 9 | name = None 10 | organizationId = None 11 | type = None 12 | 13 | def __init__(self, response): 14 | super().__init__(response) 15 | self.collectionIds = self.get_response_property_name('CollectionIds') 16 | self.name = self.get_response_property_name('Name') 17 | self.id = self.get_response_property_name('Id') 18 | self.organizationId = self.get_response_property_name('OrganizationId') 19 | self.type = self.get_response_property_name('Type') 20 | 21 | login = self.get_response_property_name('Login') 22 | if login: 23 | self.login = LoginApi(login) 24 | 25 | fields = self.get_response_property_name('Fields') 26 | if fields: 27 | self.fields = [FieldApi(field) for field in fields] 28 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/response/CipherResponse_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from bitwarden_simple_cli.models.response.CipherResponse import CipherResponse 3 | from bitwarden_simple_cli.tests.fixtures_common import common_data, cipher_response 4 | from bitwarden_simple_cli.models.api.LoginApi import LoginApi 5 | from bitwarden_simple_cli.models.api.FieldApi import FieldApi 6 | 7 | 8 | def test_base_response_get_response_property_name(cipher_response: CipherResponse): 9 | assert cipher_response.name == '2.0kujUcYqA6RWlE48DHI65A==|9dihaVyPdkV2v063b8HrIA==|fe7GxuKn3pOkAr1iCVUCt1nmBpqwzFb6FKOR51Ck2Do=' 10 | assert cipher_response.id == 'fd8870cc-3659-40aa-9492-aa3000cedbb3' 11 | assert cipher_response.organizationId is None 12 | assert cipher_response.type == 1 13 | assert isinstance(cipher_response.login, LoginApi) 14 | assert cipher_response.login.username == '2.VCFAUwS1C2y8hgD++BnDkQ==|Eh5Yno4nP6r347/GWL+/l6GQfavxtcPFBmvwzR6Tg9Q=|rghduKsyaAo75q5NLmFiHER16+Tv7Jf49zzl4ks6M14=' 15 | assert cipher_response.login.password == '2.bg59wtouG3ERlX1FThUUOA==|3/ovu/2ADKNnjpq7OjjoIttiSeqUDOrguYGcZNhKU34=|QcgJxBN6ea1Fbo3J0V8n3F9tUcAumfA3e01nDN+ihN8=' 16 | assert type(cipher_response.fields).__name__ == 'list' 17 | assert len(cipher_response.fields) == 4 18 | field = cipher_response.fields[0] 19 | assert isinstance(field, FieldApi) 20 | assert field.type == 0 21 | assert field.name == '2.8cD6Lg0308EZTEgeiuvDhQ==|rbd5+MnoZmzm9ZGI2mB0iQzJ7HysVkQFXue48eAN0eA=|vyLz6vqsIFSHdW7xQmwzbg5jm2hsUb/pS/9aIYvS1Fs=' 22 | assert field.value == '2.OEt4B5y21WB5tmkd6Gmk5w==|vXsHoRujWZj2OZNA9/iF5bIlBeWa0pI+ttr8/rgxAjA=|MZ/DDsntVddSFoY3mUPNe3JBUjCOc1ZK4PIEin9L0Oo=' 23 | 24 | 25 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/models/response/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mickaelperrin/bitwarden-decrypt-cli/43bb50ed80fe2159294bc7e191ee8756d6db7070/bitwarden_simple_cli/models/response/__init__.py -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/CipherService.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.models.domain.Cipher import Cipher 2 | from bitwarden_simple_cli.services.StorageService import StorageService 3 | from bitwarden_simple_cli.services.UserService import UserService 4 | 5 | Keys = dict( 6 | ciphersPrefix='ciphers_', 7 | localData='sitesLocalData', 8 | neverDomains='neverDomains' 9 | ) 10 | 11 | 12 | class CipherService: 13 | storageService = None 14 | userService = None 15 | 16 | def __init__(self, storage_service: StorageService, user_service: UserService): 17 | self.storageService = storage_service 18 | self.userService = user_service 19 | 20 | def get(self, uuid: str): 21 | user_id = self.userService.get_user_id() 22 | local_data = self.storageService.get(Keys['localData']) 23 | ciphers = self.storageService.get(Keys['ciphersPrefix'] + user_id) 24 | if ciphers is None or uuid not in ciphers: 25 | return None 26 | return Cipher(ciphers[uuid], False, local_data[uuid] if local_data else None) 27 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/CipherService_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from bitwarden_simple_cli.services.CipherService import CipherService 3 | from bitwarden_simple_cli.tests.fixtures_common import bw_session, cipher_service, common_data 4 | 5 | 6 | @pytest.mark.usefixtures("bw_session") 7 | def test_cipher_service(cipher_service): 8 | cipher = cipher_service.get(common_data('uuid_login_personal')) 9 | assert cipher.id == 'fd8870cc-3659-40aa-9492-aa3000cedbb3' 10 | assert cipher.organizationId is None 11 | assert cipher.userId == common_data('user_id') 12 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/ContainerService.py: -------------------------------------------------------------------------------- 1 | import bitwarden_simple_cli.services.CryptoService as CryptoService 2 | import bitwarden_simple_cli.services.SecureStorageService as SecureStorageService 3 | 4 | 5 | class ContainerService: 6 | 7 | class __ContainerService: 8 | 9 | services = dict() 10 | 11 | def add_service(self, service): 12 | self.services[type(service).__name__] = service 13 | 14 | def get_crypto_service(self) -> CryptoService.CryptoService: 15 | return self.services['CryptoService'] 16 | 17 | def get_secure_storage_service(self) -> SecureStorageService.SecureStorageService: 18 | return self.services['SecureStorageService'] 19 | 20 | def get_service(self, service): 21 | return self.services[service] 22 | 23 | instance = None 24 | 25 | @classmethod 26 | def __new__(cls, arg=None): 27 | if not ContainerService.instance: 28 | ContainerService.instance = ContainerService.__ContainerService() 29 | return ContainerService.instance 30 | 31 | def __getattr__(self, item): 32 | return getattr(self.instance, item) 33 | 34 | def __setattr__(self, key, value): 35 | return setattr(self.instance, key, value) 36 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/ContainerService_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from bitwarden_simple_cli.services.ContainerService import ContainerService 3 | from bitwarden_simple_cli.services.StorageService import StorageService 4 | from bitwarden_simple_cli.services.SecureStorageService import SecureStorageService 5 | from bitwarden_simple_cli.services.CryptoService import CryptoService 6 | from bitwarden_simple_cli.tests.fixtures_common import bw_session 7 | 8 | 9 | @pytest.mark.usefixtures("bw_session") 10 | def test_container_service(): 11 | storage_service = StorageService() 12 | crypto_service = CryptoService(storage_service) 13 | secure_storage_service = SecureStorageService(storage_service, crypto_service) 14 | container_service = ContainerService() 15 | container_service.add_service(crypto_service) 16 | container_service.add_service(secure_storage_service) 17 | container_service2 = ContainerService() 18 | assert container_service.get_crypto_service() == crypto_service 19 | assert container_service.get_secure_storage_service() == secure_storage_service 20 | assert container_service2.get_crypto_service() == crypto_service 21 | assert container_service2.get_secure_storage_service() == secure_storage_service -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/CryptoService.py: -------------------------------------------------------------------------------- 1 | from base64 import b64decode 2 | from bitwarden_simple_cli.enums.EncryptionType import EncryptionType 3 | from bitwarden_simple_cli.models.domain.CipherString import CipherString 4 | from bitwarden_simple_cli.models.domain.DecryptParameters import DecryptParameters 5 | from bitwarden_simple_cli.models.domain.SymmetricCryptoKey import SymmetricCryptoKey 6 | from bitwarden_simple_cli.services.Tools import T 7 | from cryptography.hazmat.backends import default_backend 8 | from cryptography.hazmat.primitives import hashes, serialization 9 | from cryptography.hazmat.primitives.asymmetric import padding 10 | from cryptography.hazmat.primitives.ciphers.algorithms import AES 11 | from cryptography.hazmat.primitives.ciphers.modes import CBC 12 | from cryptography.hazmat.primitives.ciphers.base import Cipher 13 | from hashlib import sha256 as hashlib_sha256 14 | from os import urandom 15 | from sys import version_info 16 | import bitwarden_simple_cli.services.ContainerService as ContainerService 17 | import bitwarden_simple_cli.services.StorageService as StorageService 18 | import hmac 19 | 20 | Keys = dict( 21 | key='key', 22 | encOrgKeys='encOrgKeys', 23 | encPrivateKey='encPrivateKey', 24 | encKey='encKey', 25 | keyHash='keyHash' 26 | ) 27 | 28 | 29 | class CryptoService: 30 | containerService: ContainerService 31 | encKey: SymmetricCryptoKey = None 32 | legacyEtmKey: SymmetricCryptoKey 33 | key: SymmetricCryptoKey = None 34 | orgKeys: [] = None 35 | privateKey: str = None 36 | secureStorageService: object 37 | storageService: StorageService 38 | 39 | def __init__(self, storage_service: StorageService): 40 | self.storageService = storage_service 41 | self.containerService = ContainerService.ContainerService() 42 | 43 | @staticmethod 44 | def aes_decrypt(data, iv, key): 45 | cipher = Cipher(AES(key), CBC(iv), default_backend()) 46 | decryptor = cipher.decryptor() 47 | plain_text = decryptor.update(data) + decryptor.finalize() 48 | padding = plain_text[len(plain_text)-1] 49 | return plain_text[:len(plain_text)-padding] 50 | 51 | def aes_decrypt_fast(self, parameters: DecryptParameters): 52 | return self.aes_decrypt(parameters.data, parameters.iv, parameters.encKey) 53 | 54 | @staticmethod 55 | def aes_decrypt_fast_parameters(data, iv, mac, key: SymmetricCryptoKey): 56 | p = DecryptParameters() 57 | p.encKey = key.encKey 58 | p.data = b64decode(data) 59 | p.iv = b64decode(iv) 60 | p.macData = p.iv + p.data 61 | 62 | if key.macKey: 63 | p.macKey = key.macKey 64 | 65 | if mac: 66 | p.mac = b64decode(mac) 67 | 68 | return p 69 | 70 | def aes_decrypt_to_bytes(self, enc_type, data, iv, mac, key): 71 | key_for_enc = self.get_key_for_encryption(key) 72 | the_key = self.resolve_legacy_key(enc_type, key_for_enc) 73 | 74 | if the_key.macKey is not None and mac is None: 75 | return None 76 | 77 | if the_key.encType != enc_type: 78 | return None 79 | 80 | if the_key.macKey and mac: 81 | mac_data = iv + data 82 | computed_mac = hmac.new(the_key.macKey, mac_data, hashlib_sha256).digest() 83 | if computed_mac is None: 84 | return None 85 | 86 | if not self.macs_compare(mac, computed_mac): 87 | T.error('mac failed') 88 | return None 89 | return self.aes_decrypt(data, iv, the_key.encKey) 90 | 91 | def aes_decrypt_to_utf8(self, enc_type, data, iv, mac, key): 92 | key_for_enc = self.get_key_for_encryption(key) 93 | the_key = self.resolve_legacy_key(enc_type, key_for_enc) 94 | 95 | if the_key.macKey is not None and mac is None: 96 | return None 97 | 98 | if the_key.encType != enc_type: 99 | T.error('encType unavailable') 100 | return None 101 | 102 | fast_params = self.aes_decrypt_fast_parameters(data, iv, mac, the_key) 103 | if fast_params.macKey and fast_params.mac: 104 | computed_mac = hmac.new(fast_params.macKey, fast_params.macData, hashlib_sha256).digest() 105 | if not self.macs_compare(computed_mac, fast_params.mac): 106 | T.error('mac failed') 107 | return None 108 | return self.aes_decrypt_fast(fast_params) 109 | 110 | def decrypt_from_bytes(self, enc_bytes, key): 111 | enc_type = EncryptionType(enc_bytes[0]) 112 | if enc_type == EncryptionType.AesCbc128_HmacSha256_B64 or enc_type == EncryptionType.AesCbc256_HmacSha256_B64: 113 | if len(enc_bytes) <= 49: 114 | return None 115 | iv = enc_bytes[1:17] 116 | mac = enc_bytes[17:49] 117 | ct = enc_bytes[49:] 118 | elif enc_type == EncryptionType.AesCbc256_B64: 119 | if len(enc_bytes) <= 17: 120 | return None 121 | iv = enc_bytes[1:17] 122 | ct = enc_bytes[17:] 123 | mac = None 124 | else: 125 | return None 126 | return self.aes_decrypt_to_bytes(enc_type, ct, iv, mac, key) 127 | 128 | def decrypt_to_bytes(self, cipher_string: CipherString, key: SymmetricCryptoKey): 129 | iv = b64decode(cipher_string.iv) 130 | data = b64decode(cipher_string.data) 131 | mac = b64decode(cipher_string.mac) if cipher_string.mac else None 132 | return self.aes_decrypt_to_bytes(cipher_string.encryptionType, data, iv, mac, key) 133 | 134 | def decrypt_to_utf8(self, cipher_string: CipherString, key: SymmetricCryptoKey): 135 | return self.aes_decrypt_to_utf8( 136 | cipher_string.encryptionType, 137 | cipher_string.data, 138 | cipher_string.iv, 139 | cipher_string.mac, 140 | key) 141 | 142 | def get_enc_key(self): 143 | if self.encKey: 144 | return self.encKey 145 | enc_key = self.storageService.get(Keys['encKey']) 146 | if enc_key is None: 147 | return None 148 | key = self.get_key() 149 | if key is None: 150 | return None 151 | enc_key_cipher = CipherString(enc_key) 152 | if enc_key_cipher.encryptionType == EncryptionType.AesCbc256_B64: 153 | dec_enc_key = self.decrypt_to_bytes(enc_key_cipher, key) 154 | elif enc_key_cipher.encryptionType == EncryptionType.AesCbc256_HmacSha256_B64: 155 | new_key = self.stretch_key(key) 156 | dec_enc_key = self.decrypt_to_bytes(enc_key_cipher, new_key) 157 | else: 158 | raise Exception('Unsupported enc_key type.') 159 | 160 | if dec_enc_key is None: 161 | return None 162 | 163 | self.encKey = SymmetricCryptoKey(dec_enc_key) 164 | return self.encKey 165 | 166 | def get_key(self): 167 | if self.key: 168 | return self.key 169 | 170 | key = self.get_secure_storage_service().get(Keys['key']) 171 | 172 | if key: 173 | self.key = SymmetricCryptoKey(b64decode(key)) 174 | 175 | return self.key if key else None 176 | 177 | def get_key_for_encryption(self, key): 178 | if key: 179 | return key 180 | enc_key = self.get_enc_key() 181 | if enc_key: 182 | return enc_key 183 | return self.get_key() 184 | 185 | def get_org_key(self, org_id): 186 | if org_id is None: 187 | return None 188 | 189 | org_keys = self.get_org_keys() 190 | if org_keys is None or org_id not in org_keys: 191 | return None 192 | 193 | return org_keys.get(org_id) 194 | 195 | def get_org_keys(self): 196 | if self.orgKeys and len(self.orgKeys) > 0: 197 | return self.orgKeys 198 | 199 | enc_org_keys = self.storageService.get(Keys['encOrgKeys']) 200 | if enc_org_keys is None: 201 | return None 202 | 203 | org_keys = {} 204 | set_key = False 205 | for orgId in enc_org_keys: 206 | if orgId not in enc_org_keys: 207 | continue 208 | dec_value = self.rsa_decrypt(enc_org_keys[orgId]) 209 | org_keys[orgId] = SymmetricCryptoKey(dec_value) 210 | set_key = True 211 | 212 | if set_key: 213 | self.orgKeys = org_keys 214 | 215 | return self.orgKeys 216 | 217 | def get_private_key(self): 218 | if self.privateKey: 219 | return self.privateKey 220 | 221 | enc_private_key = self.storageService.get(Keys['encPrivateKey']) 222 | if enc_private_key is None: 223 | return None 224 | self.privateKey = self.decrypt_to_bytes(CipherString(enc_private_key), None) 225 | return self.privateKey 226 | 227 | def get_secure_storage_service(self): 228 | return self.containerService.get_secure_storage_service() 229 | 230 | def has_key(self): 231 | return self.get_key() is not None 232 | 233 | # ref: https://github.com/casebeer/python-hkdf/blob/master/hkdf.py 234 | @staticmethod 235 | def hkdf_expand(pseudo_random_key, info=b"", length=32, selected_hash=hashes.SHA256): 236 | if version_info[0] == 3: 237 | buffer = lambda x: x 238 | ''' 239 | Expand `pseudo_random_key` and `info` into a key of length `bytes` using 240 | HKDF's expand function based on HMAC with the provided hash (default 241 | SHA-512). See the HKDF draft RFC and paper for usage notes. 242 | ''' 243 | hash_len = selected_hash().digest_size 244 | length = int(length) 245 | if length > 255 * hash_len: 246 | raise Exception("Cannot expand to more than 255 * %d = %d bytes using the specified hash function" % 247 | (hash_len, 255 * hash_len)) 248 | blocks_needed = length // hash_len + (0 if length % hash_len == 0 else 1) # ceil 249 | okm = b"" 250 | output_block = b"" 251 | for counter in range(blocks_needed): 252 | output_block = hmac.new(pseudo_random_key, buffer(output_block + info + bytearray((counter + 1,))), 253 | selected_hash.name).digest() 254 | okm += output_block 255 | return okm[:length] 256 | 257 | @staticmethod 258 | def macs_compare(a, b): 259 | key = urandom(32) 260 | hmac1 = hmac.new(key, a, hashlib_sha256).digest() 261 | hmac2 = hmac.new(key, b, hashlib_sha256).digest() 262 | return hmac.compare_digest(hmac1, hmac2) 263 | 264 | def resolve_legacy_key(self, enc_type: EncryptionType, key: SymmetricCryptoKey) -> SymmetricCryptoKey: 265 | if enc_type == EncryptionType.AesCbc128_HmacSha256_B64 and key.encType == EncryptionType.AesCbc256_B64: 266 | if self.legacyEtmKey is None: 267 | self.legacyEtmKey = SymmetricCryptoKey(key.key, EncryptionType.AesCbc128_HmacSha256_B64) 268 | return self.legacyEtmKey 269 | return key 270 | 271 | def rsa_decrypt(self, enc_value): 272 | header_pieces = enc_value.split('.') 273 | enc_type: EncryptionType = None 274 | enc_pieces = None 275 | 276 | if len(header_pieces) == 1: 277 | enc_type = EncryptionType.Rsa2048_OaepSha256_B64 278 | enc_pieces = [header_pieces[0]] 279 | elif len(header_pieces) == 2: 280 | try: 281 | enc_type = EncryptionType(int(header_pieces[0])) 282 | enc_pieces = header_pieces[1].split('|') 283 | except Exception as e: 284 | T.error(e) 285 | 286 | if enc_type != EncryptionType.Rsa2048_OaepSha256_B64 \ 287 | and enc_type != EncryptionType.Rsa2048_OaepSha1_B64 \ 288 | and enc_type != EncryptionType.Rsa2048_OaepSha256_HmacSha256_B64 \ 289 | and enc_type != EncryptionType.Rsa2048_OaepSha1_HmacSha256_B64: 290 | raise Exception('encType unavailable') 291 | 292 | if enc_pieces is None or len(enc_pieces) <= 0: 293 | raise Exception('encPieces unavailable') 294 | 295 | data = b64decode(enc_pieces[0]) 296 | private_key = self.get_private_key() 297 | if private_key is None: 298 | raise Exception('No private key') 299 | 300 | if enc_type == EncryptionType.Rsa2048_OaepSha256_B64 \ 301 | or enc_type == EncryptionType.Rsa2048_OaepSha256_HmacSha256_B64: 302 | alg = hashes.SHA256() 303 | elif enc_type == EncryptionType.Rsa2048_OaepSha1_B64 \ 304 | or enc_type == EncryptionType.Rsa2048_OaepSha1_HmacSha256_B64: 305 | alg = hashes.SHA1() 306 | else: 307 | raise Exception('encType unavailable.') 308 | 309 | return serialization\ 310 | .load_der_private_key(private_key, None, default_backend())\ 311 | .decrypt(data, 312 | padding.OAEP( 313 | mgf=padding.MGF1( 314 | algorithm=alg, 315 | ), 316 | algorithm=alg, 317 | label=None 318 | )) 319 | 320 | def stretch_key(self, key: SymmetricCryptoKey): 321 | new_key = self.hkdf_expand(key.key, b'enc', 32) + self.hkdf_expand(key.key, b'mac', 32) 322 | return SymmetricCryptoKey(new_key) 323 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/CryptoService_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from bitwarden_simple_cli.services.CryptoService import CryptoService 3 | from bitwarden_simple_cli.models.domain.SymmetricCryptoKey import SymmetricCryptoKey 4 | from bitwarden_simple_cli.tests.fixtures_common import bw_session, crypto_service 5 | from bitwarden_simple_cli.services.ContainerService import ContainerService 6 | from bitwarden_simple_cli.services.SecureStorageService import SecureStorageService 7 | 8 | 9 | @pytest.mark.usefixtures("bw_session") 10 | def test_has_key(crypto_service: CryptoService): 11 | # ensure we use the test database in secure storage service 12 | ContainerService().add_service(SecureStorageService(crypto_service.storageService, crypto_service)) 13 | assert crypto_service.has_key() == True 14 | 15 | 16 | @pytest.mark.usefixtures("bw_session") 17 | def test_get_key(crypto_service: CryptoService): 18 | # ensure we use the test database in secure storage service 19 | ContainerService().add_service(SecureStorageService(crypto_service.storageService, crypto_service)) 20 | key = crypto_service.get_key() 21 | assert key is not None 22 | assert isinstance(key, SymmetricCryptoKey) 23 | assert key.encType.value == 0 24 | assert key.keyB64 == b'/lCGAMDGAq+mjRP3FJv+VNDDnbrYcVGnsiPeXTm4NfU=' 25 | assert key.encKeyB64 == b'/lCGAMDGAq+mjRP3FJv+VNDDnbrYcVGnsiPeXTm4NfU=' -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/SecureStorageService.py: -------------------------------------------------------------------------------- 1 | from base64 import b64decode, b64encode 2 | from bitwarden_simple_cli.models.domain.SymmetricCryptoKey import SymmetricCryptoKey 3 | from bitwarden_simple_cli.services.CryptoService import CryptoService 4 | from bitwarden_simple_cli.services.StorageService import StorageService 5 | from bitwarden_simple_cli.services.Tools import T 6 | from os import environ as os_environ 7 | 8 | 9 | class SecureStorageService: 10 | 11 | cryptoService: CryptoService 12 | storageService: StorageService 13 | 14 | def __init__(self, storage_service: StorageService, crypto_service: CryptoService): 15 | self.cryptoService = crypto_service 16 | self.storageService = storage_service 17 | 18 | def decrypt(self, enc_value) -> str: 19 | try: 20 | session_key = self._get_session_key() 21 | if session_key is None: 22 | return '' 23 | dec_value = self.cryptoService.decrypt_from_bytes(b64decode(enc_value), session_key) 24 | if dec_value is None: 25 | T.error('Failed to decrypt') 26 | return '' 27 | return b64encode(dec_value) 28 | except Exception as e: 29 | T.error(e) 30 | T.error('Decrypt error') 31 | 32 | def get(self, key: str): 33 | value = self.storageService.get(self._make_protected_storage_key(key)) 34 | if value is None: 35 | return None 36 | return self.decrypt(value) 37 | 38 | @staticmethod 39 | def _get_session_key(): 40 | try: 41 | if os_environ.get('BW_SESSION'): 42 | return SymmetricCryptoKey(b64decode(os_environ['BW_SESSION'])) 43 | except Exception as e: 44 | T.error(e) 45 | print('Session key is invalid.') 46 | return None 47 | 48 | @staticmethod 49 | def _make_protected_storage_key(key) -> str: 50 | return '__PROTECTED__' + key 51 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/SecureStorageService_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from bitwarden_simple_cli.tests.fixtures_common import common_data, secure_storage_service, bw_session 3 | 4 | 5 | @pytest.mark.usefixtures("bw_session") 6 | def test_secure_storage_service_get(secure_storage_service): 7 | assert secure_storage_service.get('userId') is None 8 | assert secure_storage_service.get('key') == b'/lCGAMDGAq+mjRP3FJv+VNDDnbrYcVGnsiPeXTm4NfU=' 9 | 10 | 11 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/StorageService.py: -------------------------------------------------------------------------------- 1 | from os import environ, path as os_path 2 | from platform import system 3 | from json import load as json_load 4 | from bitwarden_simple_cli.models.domain.CipherString import CipherString 5 | 6 | 7 | class StorageService: 8 | 9 | app_path: str 10 | database_path: str 11 | database_filename: str = 'data.json' 12 | 13 | def __init__(self, database_path=None): 14 | self.database_path = self.set_database_path(database_path) 15 | self.database = self._read_datase_file() 16 | 17 | def get(self, key): 18 | return self.database.get(key) 19 | 20 | @staticmethod 21 | def guess_database_dir(): 22 | if environ.get('BITWARDENCLI_APPDATA_DIR'): 23 | path = environ.get('BITWARDENCLI_APPDATA_DIR') 24 | elif system() == 'Linux': 25 | path = environ.get('XDG_CONFIG_HOME') 26 | elif system() == 'Darwin': 27 | path = os_path.join(environ.get('HOME'), 'Library/Application Support/Bitwarden CLI') 28 | elif system() == 'Windows': 29 | path = os_path.join(environ.get('APPDATA'), 'Bitwarden CLI') 30 | else: 31 | path = None 32 | 33 | if path is not None and path != '': 34 | return path 35 | else: 36 | return os_path.join(environ.get('HOME'), '.config/Bitwarden CLI') 37 | 38 | def list_ciphers(self, user_id): 39 | ciphers = self.database.get('ciphers_' + user_id) 40 | list = [] 41 | for k, cipher in ciphers.items(): 42 | list.append(dict(id=cipher['id'], name=CipherString(cipher['name']), org_id=cipher.get('organizationId'))) 43 | return list 44 | 45 | def _read_datase_file(self): 46 | with open(self.database_path, 'r') as fp: 47 | try: 48 | database = json_load(fp) 49 | return database 50 | except ValueError: 51 | print("error loading JSON") 52 | 53 | def set_database_path(self, path): 54 | if path is None: 55 | return self.set_database_path(os_path.join(self.guess_database_dir(), self.database_filename)) 56 | if os_path.isfile(path): 57 | return path 58 | raise Exception('Database file not found at ' + path) 59 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/StorageService_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pytest 3 | from bitwarden_simple_cli.services.StorageService import StorageService 4 | from bitwarden_simple_cli.tests.fixtures_common import storage_service, common_data 5 | 6 | 7 | def test_storage_service_init_without_db_path(): 8 | storage_service = StorageService() 9 | assert os.path.isfile(storage_service.database_path) 10 | 11 | 12 | @pytest.mark.usefixtures("storage_service") 13 | def test_storage_service_init_without_db_path(storage_service): 14 | assert os.path.isfile(storage_service.database_path) 15 | assert os.path.basename(storage_service.database_path) == common_data('test_database_filename') 16 | assert storage_service.database is not None 17 | assert storage_service.database.get('userEmail') == common_data('user_email') 18 | assert storage_service.database.get('userId') == common_data('user_id') 19 | assert storage_service.database.get('__PROTECTED__key') == common_data('protected_key') 20 | assert 'ciphers_' + common_data('user_id') in storage_service.database 21 | assert 'organizations_' + common_data('user_id') in storage_service.database 22 | assert common_data('organization_id') in storage_service.database['organizations_' + common_data('user_id')] 23 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/Tools.py: -------------------------------------------------------------------------------- 1 | import os 2 | if os.environ.get('DEBUG'): 3 | import logging 4 | import pprint as pp 5 | log = logging.getLogger("bitwarden") 6 | log.propagate = True 7 | 8 | 9 | class T: 10 | 11 | @staticmethod 12 | def debug2(msg, name=''): 13 | if name: 14 | msg = name + ': ' + msg 15 | if os.environ.get('DEBUG'): 16 | log.log(5, pp.pformat(msg)) 17 | 18 | @staticmethod 19 | def debug(msg, name=''): 20 | if name: 21 | msg = name + ': ' + msg 22 | if os.environ.get('DEBUG'): 23 | log.debug(pp.pformat(msg)) 24 | 25 | @staticmethod 26 | def info(msg, name=''): 27 | if name: 28 | msg = name + ': ' + msg 29 | if os.environ.get('DEBUG'): 30 | log.info(pp.pformat(msg)) 31 | 32 | @staticmethod 33 | def error(msg): 34 | if os.environ.get('DEBUG'): 35 | log.error(msg) 36 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/UserService.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.services.StorageService import StorageService 2 | 3 | 4 | class UserService: 5 | 6 | email = None 7 | stamp = None 8 | storageService = None 9 | userId = None 10 | 11 | def __init__(self, storage_service: StorageService): 12 | self.storageService = storage_service 13 | 14 | def get_user_id(self): 15 | if self.userId: 16 | return self.userId 17 | self.userId = self.storageService.get('userId') 18 | return self.userId 19 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/UserService_test.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.services.UserService import UserService 2 | from bitwarden_simple_cli.tests.fixtures_common import user_service, common_data 3 | 4 | 5 | def test_cipher_service(user_service: UserService): 6 | assert user_service.get_user_id() == common_data('user_id') 7 | -------------------------------------------------------------------------------- /bitwarden_simple_cli/services/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mickaelperrin/bitwarden-decrypt-cli/43bb50ed80fe2159294bc7e191ee8756d6db7070/bitwarden_simple_cli/services/__init__.py -------------------------------------------------------------------------------- /bitwarden_simple_cli/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mickaelperrin/bitwarden-decrypt-cli/43bb50ed80fe2159294bc7e191ee8756d6db7070/bitwarden_simple_cli/tests/__init__.py -------------------------------------------------------------------------------- /bitwarden_simple_cli/tests/data.json: -------------------------------------------------------------------------------- 1 | { 2 | "installedVersion": "1.7.2", 3 | "appId": "ae7f4073-189f-4de3-95e8-6fedd13b833e", 4 | "lastSync_bf3d116e-1f0a-4c23-96d7-aa2900dac0d3": "1970-01-01T00:00:00.000Z", 5 | "accessToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6IkJDMzZDMjE0REI0OEYyMzVCNzdEQTNGMTcyMEMxQTM1QTk2MkVBNDMiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJ2RGJDRk50SThqVzNmYVB4Y2d3YU5hbGk2a00ifQ.eyJuYmYiOjE1NTUzMzI1MzEsImV4cCI6MTU1NTMzNjEzMSwiaXNzIjoiaHR0cHM6Ly9pZGVudGl0eS5iaXR3YXJkZW4uY29tIiwiYXVkIjpbImh0dHBzOi8vaWRlbnRpdHkuYml0d2FyZGVuLmNvbS9yZXNvdXJjZXMiLCJhcGkiXSwiY2xpZW50X2lkIjoiY2xpIiwic3ViIjoiMDM3ODAyNDYtN2YxZC00MjIxLTg2MTUtYWEzMDAwY2Q4MTIzIiwiYXV0aF90aW1lIjoxNTU1MzMyNTMxLCJpZHAiOiJiaXR3YXJkZW4iLCJwcmVtaXVtIjpmYWxzZSwiZW1haWwiOiJkZXYrYml0d2FyZGVuQG1pY2thZWxwZXJyaW4uZnIiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwic3N0YW1wIjoiVTNOSkk3SFFEVEZJVDZYNkpKWEhJTDZDTFpUUENBSU4iLCJuYW1lIjoibWlja2FlbHBlcnJpbl9kZXYiLCJvcmdvd25lciI6IjFmZjUxY2NkLTBhMjUtNDZhMi1hM2NkLWFhMzAwMGNmYTg3NCIsImRldmljZSI6ImFlN2Y0MDczLTE4OWYtNGRlMy05NWU4LTZmZWRkMTNiODMzZSIsInNjb3BlIjpbImFwaSIsIm9mZmxpbmVfYWNjZXNzIl0sImFtciI6WyJBcHBsaWNhdGlvbiJdfQ.PL8gWAn_rNekZAxOyn9fuo55NGwhUO0tSfd6qwch7qD_rkRVLONllId3pVr_eqVk2LW8qDE3bsUTSeQINz0IwKmQ3n16vLfT780ExOhb58o0FJwMu28kY1dJNL2cUJiXP0ZAHoEthvX6o0a8OEkZF_-7pDBwkuY2apwZ8nSbismsXiasucszjDHzTcbEDHtQshOS8wVynjU6bS1G_axEUGHpHGbsiE1eEfwijh-tRAkCaEDxUT9NwOD0ZquekKv2xUiqBGTjSiaqlSqeoQQ2Pp7ZNOsSsfrjxreVUsOzwj4-eUMyo30yMU4YzzukIu-JOHd5ftLPrEMC417mzL_gd610cjnRXbMIRTLm-wyY5QJdOQWhQkLSboevPJkMhj7oHHp3i7NtXRLwrdQuNP4qZhiVdKPsw2XUNSgrCEFAvfEab5T4v_xmMn5IKHbHLK2Fy3TQBPH6RUvUpXvS1P5hxR2zXRjoL-xelY6pRlClkachEYBbXsVf7Gtx5SZE_-Vzzpkd5FnCE4t7fiyAoUSiVfBgeooPEP2Pkeky9KfiMpg0qWvrBDO5dn9woZ57j2OVT16vEVKKJPpY4m7_LIM0sQGBdgI83X1_sNF5yJKaK-Hb5DAq3ArKPIFFN6mgVyamc5y0SKH51pXGqjGqJ-HH3h5SpJITgyMvnL9ybLsFCtI", 6 | "refreshToken": "dc5e451fd391cb274971f59e99749cdf0cd55cde13d6f7225f3ead1a9e2b2bcf", 7 | "userEmail": "dev+bitwarden@mickaelperrin.fr", 8 | "userId": "03780246-7f1d-4221-8615-aa3000cd8123", 9 | "kdf": 0, 10 | "kdfIterations": 100000, 11 | "__PROTECTED__key": "ArxoewBOPtCYZKqn34f8CoMQVUrNZnrhGU9OYuJu8UpB7DngEwf/TEHjbxPJJhUDG+DnPQR76J9d12/4tnGT5C6ZaLxxInRooT4AuX2ljIrSppCee1AvzIMu7ljGhR++ng==", 12 | "keyHash": "FMxYnEQUonQzcTc/em7WXu51fg40gyXuTQDZk35tHyI=", 13 | "encKey": "2.fesomqaetmlrUyLLEjXRqA==|9X3ZE1POGlaNzxUwMzZn6wzAw1Mv3ihIsi2SZSVhFNXuF/P699mbhACMRruf/NxzLOIwUIxMvdl653WJkYIHxUHCBFat0tbfBrVD3IX65xE=|Ls4TzYcn7Hkw6/N/YQ1oXyMp/2W+xT24fkfLQW1CX58=", 14 | "encPrivateKey": "2.HOR4NpQ+kE9iHvNqOi4QcA==|0+m4T/AeII0yzR9Tj2typ1SQ+/RRR4fVcCL3GP1qloRaywYph3LTyHSfv0a1aYPZsl8DenCjFc4swj2utXiBxBGF4ILB1M3fKpM40/mQwvwD+FY9mFOnO1uv8i561X8qil5lcHnoAzXv2kvArcHIr00Fy1ZTrA/Pn+OA3dl6nxCHEnNGpw1lhm1yFqKcamhgNrnvHBAhjU01vqk/yILBHjocfaCKr6BsaUcIoQInYTCTOPoRAa6evHGsZY6Kb99wjUCBvSHiD3/OekUW6/4PNWcGdVLao/hApGcj1MBMkyK39B/i9stvi5Q2mdHoJk1+Gqnwm3jpSbKWwGK/fkkBdMlKxxxpgsfGPEuSFOIO1q5d0CD5A1ELt68DysKXy154MRf+V39i748mUf/Iif6bxwEd5YhTri05by4UlMbKFvx3zl/bNPFtg/xV/c6LWPPqExVIWZOfs65NwDXpXQiiAQgg9/gUuOcr+Kq4zwjt61K7F93Q5RtKNy7rCVK5WAww0E7a+5kWSsxDusy+Cx+wEU9jTOIgAlP773q7+KGxaESvb7/z6AQMJBHTud0O5exXHm2fPMbk2JLBFYIvmfQGpKxzGTYR3/+R6NqmeO/Ra0Uu4KRpYdK8vitO/3KOIE0xChPHhIGDwv/ejtPHzqVwxsnw8sKujXVa+8OQNbs6SJ+dRB5LybbN3e5fzJIewEhteWnwXcJoPBt+hZkKVX7AhemolLGuTjU2DyCEO58/cY30T5sY/ymqf6TvWoppbiNss50ygmXGoxCevMxjmWGtrT+Q33/VlhC94ZrN1aCe0Je1poPVJd7XNhjuV5Uo/pC3lGXhGPCwq5AtMSMgGbKKOtnFjfYSx8pewbZDaHeWKerlNSWdd9dWhtzXFi0un6+3GM5Qcnn7VhQULcF0kn7dFbCIkxpGKfb/OFo3LchBzjnkywV9iDHuAI8f4j4MHNMn4r7mzq9xf9ugVdURoVT2F59Z1wNNm5NAhFxfOK/AU6RVo6e/xE3X4x47u0dqwMzkLpQZ82yIkk1/4RYOXdE5EEEcbhhq6FQ+cTlM3V8yF32k6zmKef5cTrDI2VatPmbQUNpV6S3vltj6biXysOvkaTd/c/JlPV42DuxIFDreJlb2IpJY4jeW8Om+g8/mtkrNsTEmod2f7CNhFw7F2gipBsyMgeiHJtpkJeMCDT2C2UZH/yzP9Ygo1xp9zZI9CdwZ7zG4g2VmJRp29iX1uwDLtSf+2BO7Y1tTuHBbogkCrg2fkeKiD24+gVR+AausGmgMgc/cyinIEE3btvFMoM3Skuuq7wu8AxuphPZzHUa+IPRcWJ7ahpB9o4ngpejQ7rTBns1UWBxkD32y0XwzG+/A1PhCAyoYD8fUkk1atC4G4FlCN8bGmU0AK1rqn8WJJ7T4uiWIBm/INoV520F0pqzlokVE7OC+LDDHlI/QX/54nttv5q1k/5501OVxI1efl4jCIlwWvAOFQ/x2qWmcvEC8mys8tvW1btC54QogKWmVwuMU4zA3dvg7lQWKSwBXlKUZU0xzFLVe84juIvIpiWzhjxgVgZQavnfj1kCQWxwXKFxVXAj9tEfQPbAHTA70pXt2Rod0Y5jwYeaRXkC94Wv7Ux7edeoUe8q94d6RuSzRoLg=|SKI7eVzSZjdUBoCe/xhJqMFqKrnqR8Du0emrSBhuBWs=", 15 | "encOrgKeys": { 16 | "1ff51ccd-0a25-46a2-a3cd-aa3000cfa874": "4.c9tF/JR0OMhj0K+eqsiAbeEDGbgQ9HLXLZQ+ombYHKF6DeOoqELqCV+SN9fTr7/JMk/orFAQJrTghB/ByXAp9nkM2E4Ejg3chNiu4iDMi7cHusyl2+9+6jRd8vYZcs3+QQbCUYGIPhnMbGCpiTwFa/Jfck/9z6HvtAAKvGwCe3eqfNvuRLGMkGlwIGGcfqe/xlOCGuqgpIBBCPLFG9Ge9LttDq3ep7wU4yST0xsJ/URu02Q3dBF/OI44BNoZTZYG/J0pMaQNUbLxDfmSOl+14CmCeSF8Aq03lKoBNyYU50QB3tgiE9u9kuBvYT+mxQAw8aTtB+3PIKAXt+kqDsrzbQ==" 17 | }, 18 | "securityStamp": "U3NJI7HQDTFIT6X6JJXHIL6CLZTPCAIN", 19 | "organizations_03780246-7f1d-4221-8615-aa3000cd8123": { 20 | "1ff51ccd-0a25-46a2-a3cd-aa3000cfa874": { 21 | "id": "1ff51ccd-0a25-46a2-a3cd-aa3000cfa874", 22 | "name": "ACME", 23 | "status": 2, 24 | "type": 0, 25 | "enabled": true, 26 | "useGroups": false, 27 | "useDirectory": false, 28 | "useEvents": false, 29 | "useTotp": false, 30 | "use2fa": false, 31 | "useApi": false, 32 | "selfHost": false, 33 | "usersGetPremium": false, 34 | "seats": 2, 35 | "maxCollections": 2, 36 | "maxStorageGb": null 37 | } 38 | }, 39 | "folders_03780246-7f1d-4221-8615-aa3000cd8123": {}, 40 | "collections_03780246-7f1d-4221-8615-aa3000cd8123": { 41 | "94c2ec08-fbfa-4896-ad34-aa3000cfa877": { 42 | "id": "94c2ec08-fbfa-4896-ad34-aa3000cfa877", 43 | "organizationId": "1ff51ccd-0a25-46a2-a3cd-aa3000cfa874", 44 | "name": "2.uIHpaDgsBMKAa0JnvncYzQ==|unExmXpmFaCs5EHQwXdHzuR+Vf3qTSfpdV+gWr8ov1A=|eJUdCYIyC1fRcuhB8X3gpMUgGyBHOHT//+fltRw+Sy0=", 45 | "externalId": null, 46 | "readOnly": false 47 | } 48 | }, 49 | "ciphers_03780246-7f1d-4221-8615-aa3000cd8123": { 50 | "fe6e74aa-a099-4cc1-ae8e-aa3000d02c14": { 51 | "id": "fe6e74aa-a099-4cc1-ae8e-aa3000d02c14", 52 | "organizationId": "1ff51ccd-0a25-46a2-a3cd-aa3000cfa874", 53 | "folderId": null, 54 | "userId": "03780246-7f1d-4221-8615-aa3000cd8123", 55 | "edit": true, 56 | "organizationUseTotp": false, 57 | "favorite": false, 58 | "revisionDate": "2019-04-15T12:37:55.9033333Z", 59 | "type": 1, 60 | "name": "2.Q85+9mcYOqEuNLcMdRR8UA==|odhHCal7gXyfFiAXNh+xYw==|TT+z/ggpaL3XUQrm5z477nBCL7AzvD9lOH4F/AZ+L+k=", 61 | "notes": "2.soN/BH23YOnXSIYP0qEraQ==|l/1XSbQ0FewPphmA5Z4xYLpcgv0iMet4vkPkxmwBKJM=|C4MvC6ylhVs9lXbdioUtyv75rbEgV9QZK1jbW+pSARc=", 62 | "collectionIds": [ 63 | "94c2ec08-fbfa-4896-ad34-aa3000cfa877" 64 | ], 65 | "login": { 66 | "username": "2./PgIXWwkwRHRkcecxkPXnA==|ogCNCBxvyBEC8zzkucxwrw==|h3sY6FTi1RoXyV9oPe5U9IEk+sg9PehMHPyML6hiv0o=", 67 | "password": "2.raInZgMFvuBKXzzPVidr+w==|mUq0NMJmDcqAc8zalhHvIa7porEZoA6FcUR1nrES4vI=|jxMuzThXPzxjPcru0Fuvu5pSeoEHk3e5j8KA5LywVdk=", 68 | "passwordRevisionDate": null, 69 | "totp": null, 70 | "uris": [ 71 | { 72 | "match": null, 73 | "uri": "2.uxH9HmpNS4sMI+PGK2bTKQ==|UiZoUkwSKH/sSc8tmpJPLL7RA0yDN0qkJfckoJnS9f0=|vXKiYRsBq5wjbf8YCpzbFU3jUHrI2wdO87IPFNCx4Qo=" 74 | }, 75 | { 76 | "match": null, 77 | "uri": "2.LRTUZ3yHiz5dVc9cCov/7w==|O9QS38DToMbiqxNciOx5p0L+OFG5DY8wBXD06NrEcNw=|x7Bq78kTTxCLsbEiM9VLZOpq89BugMpZ200B7klFz7U=" 78 | } 79 | ] 80 | }, 81 | "fields": [ 82 | { 83 | "type": 0, 84 | "name": "2.V+/tDC/KasHckRH4fkYOmg==|6LskpOZMnDkxmgiyuLd2oIDU4yvCfrZMjlHzrSYciqY=|hrf11CSMQKDwGSFJ1wJ4ltPQahQankT3ccaJ3ghURec=", 85 | "value": "2.6+XNNUrEj4VtV79g/Piz5A==|pUWSK03bCV/jiQgwN4DLNlTPffO1bFxKw5qfuvSx0GIzUYTM6cSb/rSE3YJ8DQia|PEciBs8yoSfj7t3wzEQ0y+LilFvE2Z3PsL9dfBDOlI8=" 86 | } 87 | ] 88 | }, 89 | "fd8870cc-3659-40aa-9492-aa3000cedbb3": { 90 | "id": "fd8870cc-3659-40aa-9492-aa3000cedbb3", 91 | "organizationId": null, 92 | "folderId": null, 93 | "userId": "03780246-7f1d-4221-8615-aa3000cd8123", 94 | "edit": true, 95 | "organizationUseTotp": false, 96 | "favorite": false, 97 | "revisionDate": "2019-04-15T12:33:08.86Z", 98 | "type": 1, 99 | "name": "2.0kujUcYqA6RWlE48DHI65A==|9dihaVyPdkV2v063b8HrIA==|fe7GxuKn3pOkAr1iCVUCt1nmBpqwzFb6FKOR51Ck2Do=", 100 | "notes": "2.UEB/CebzJLPkgGJ0htun1g==|bX5nHZtvkMKl3b/7OHCuOg==|m9j9A/HDG5Rw4bO2bHCVeQ3tMYT1ij85tZIw2DPbk0k=", 101 | "collectionIds": [], 102 | "login": { 103 | "username": "2.VCFAUwS1C2y8hgD++BnDkQ==|Eh5Yno4nP6r347/GWL+/l6GQfavxtcPFBmvwzR6Tg9Q=|rghduKsyaAo75q5NLmFiHER16+Tv7Jf49zzl4ks6M14=", 104 | "password": "2.bg59wtouG3ERlX1FThUUOA==|3/ovu/2ADKNnjpq7OjjoIttiSeqUDOrguYGcZNhKU34=|QcgJxBN6ea1Fbo3J0V8n3F9tUcAumfA3e01nDN+ihN8=", 105 | "passwordRevisionDate": null, 106 | "totp": null, 107 | "uris": [ 108 | { 109 | "match": null, 110 | "uri": "2.kS2d1arj/MM9h+mIW9RMAQ==|CNdUog9M8mByYXTFgkbYRg==|RC89j2K9sNcxqDf9f+aujnQm0LRNwXvqKQK0lIipDXQ=" 111 | }, 112 | { 113 | "match": null, 114 | "uri": "2.XnKvUBwgh4rVhlc2Kswqgg==|FCGHFqpj5jOWnS+SCmvF/A==|TPiRhI4mAZg05wEyXV7VdCbiQo0EVZ0BagDJrvxWcOw=" 115 | } 116 | ] 117 | }, 118 | "fields": [ 119 | { 120 | "type": 0, 121 | "name": "2.8cD6Lg0308EZTEgeiuvDhQ==|rbd5+MnoZmzm9ZGI2mB0iQzJ7HysVkQFXue48eAN0eA=|vyLz6vqsIFSHdW7xQmwzbg5jm2hsUb/pS/9aIYvS1Fs=", 122 | "value": "2.OEt4B5y21WB5tmkd6Gmk5w==|vXsHoRujWZj2OZNA9/iF5bIlBeWa0pI+ttr8/rgxAjA=|MZ/DDsntVddSFoY3mUPNe3JBUjCOc1ZK4PIEin9L0Oo=" 123 | }, 124 | { 125 | "type": 1, 126 | "name": "2.p0BEx6HRXvfA+0TeHFi4nA==|UW5dXnW4rlQocnHOTcLM/FOlQLbjQh/k+g65Yrh6COw=|jq42Sp0sgs6H+DyuLEDQ5UY7sbRj4DYMr8PAVD5G+OU=", 127 | "value": "2.si7K0uetUvT5BUAeFskx9Q==|4iKxRN3/6TUfhRWXGQijsaS3K7NTlE5v04WqhfeCcH8=|Dgo2TwZHRxeyLID/LkKBQIPvc5IJatbupFOiIc15K4E=" 128 | }, 129 | { 130 | "type": 2, 131 | "name": "2.49fH9DjGRS6RRTL4I9zZSg==|/k3uffKs1wQbdQU1oFnt6YbBHVtd/tl2XQQQbkPdtWM=|2vrIYiZnFhHk0hx0lNdIo8FkQDKJlmDRIDDpj9hyvhw=", 132 | "value": "2.53eXq9PhlhbUH1QASmZvKg==|djHCRO2WazzxcL2mjzxF5Q==|UVXokiiqBb/9rb/VQ+gOa6PpV0iifc1Ye5AhHMqClG0=" 133 | }, 134 | { 135 | "type": 2, 136 | "name": "2.QDn0bwKJbEgjWAATLJqWAg==|Csoq4Sr6O8byHZoiU70PwyBt9txNTN2Fjz2sl9ZD190=|nwzx3YGpgxk2Tu/bg0M8CEF+yHU4zhjfQOGxjSZVpUQ=", 137 | "value": "2.zGBCnWTtRfxuuwdr8MstVw==|RX24BmIJvcef9/A95Idbhg==|jr+Wp+kiBsvAp/HbsXRxr1WSqNDnyQATfdl9Y2nuTBU=" 138 | } 139 | ] 140 | }, 141 | "450cbad2-580b-4523-bce8-aa3000cf641a": { 142 | "id": "450cbad2-580b-4523-bce8-aa3000cf641a", 143 | "organizationId": null, 144 | "folderId": null, 145 | "userId": "03780246-7f1d-4221-8615-aa3000cd8123", 146 | "edit": true, 147 | "organizationUseTotp": false, 148 | "favorite": false, 149 | "revisionDate": "2019-04-15T12:35:18.85Z", 150 | "type": 2, 151 | "name": "2.TTcqehXSTXWWQ+ZbaEzM9Q==|yVBEAsb2RXK+gyE2Ksgf2A==|nelj2sR6FtXPAj8/39BfjhvDFX5fBVAlBU76ie5aBM8=", 152 | "notes": "2.7oQBZuRisr4ZPwBnORQBtA==|baaXjw+6N78CujdEVHibng==|BUY4hDxAPANX2XctsBZQFko4sQeFfQ5fLSGGjqIb05o=", 153 | "collectionIds": [], 154 | "secureNote": { 155 | "type": 0 156 | }, 157 | "fields": [ 158 | { 159 | "type": 0, 160 | "name": "2.SAT7ye1/oDl+cy0Q9pspqQ==|VdWCs7f6V75odrQy5UrsIJRnu9A3zQy7HfTmBsKA0xQ=|R9NMJTRI53drSdxShOlvKT5D2odFQ9Dw9xE1Ixedp7U=", 161 | "value": "2.CPiQIz0+jqrNln/wPcDA9Q==|BhN//oDzIDIUrm7JF9RKLupVbeNDZxMszJlJHiUDSLE=|ca9lzItbf97APY9ZL0Lq6e+Si3xHbq8GOEliUbHMl0o=" 162 | } 163 | ] 164 | } 165 | }, 166 | "settings_03780246-7f1d-4221-8615-aa3000cd8123": { 167 | "equivalentDomains": [] 168 | }, 169 | "lastSync_03780246-7f1d-4221-8615-aa3000cd8123": "2019-04-15T12:49:23.564Z" 170 | } -------------------------------------------------------------------------------- /bitwarden_simple_cli/tests/fixtures_common.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from json import loads as json_loads 3 | from os import path, environ 4 | from bitwarden_simple_cli.services.StorageService import StorageService 5 | from bitwarden_simple_cli.services.SecureStorageService import SecureStorageService 6 | from bitwarden_simple_cli.services.CryptoService import CryptoService 7 | from bitwarden_simple_cli.services.UserService import UserService 8 | from bitwarden_simple_cli.services.CipherService import CipherService 9 | from bitwarden_simple_cli.models.response.CipherResponse import CipherResponse 10 | 11 | 12 | def common_data(item): 13 | cipher_response = '{ \ 14 | "id": "fd8870cc-3659-40aa-9492-aa3000cedbb3",\ 15 | "organizationId": null,\ 16 | "folderId": null,\ 17 | "userId": "03780246-7f1d-4221-8615-aa3000cd8123",\ 18 | "edit": true,\ 19 | "organizationUseTotp": false,\ 20 | "favorite": false,\ 21 | "revisionDate": "2019-04-15T12:33:08.86Z",\ 22 | "type": 1,\ 23 | "name": "2.0kujUcYqA6RWlE48DHI65A==|9dihaVyPdkV2v063b8HrIA==|fe7GxuKn3pOkAr1iCVUCt1nmBpqwzFb6FKOR51Ck2Do=",\ 24 | "notes": "2.UEB/CebzJLPkgGJ0htun1g==|bX5nHZtvkMKl3b/7OHCuOg==|m9j9A/HDG5Rw4bO2bHCVeQ3tMYT1ij85tZIw2DPbk0k=",\ 25 | "collectionIds": [],\ 26 | "login": {\ 27 | "username": "2.VCFAUwS1C2y8hgD++BnDkQ==|Eh5Yno4nP6r347/GWL+/l6GQfavxtcPFBmvwzR6Tg9Q=|rghduKsyaAo75q5NLmFiHER16+Tv7Jf49zzl4ks6M14=", \ 28 | "password": "2.bg59wtouG3ERlX1FThUUOA==|3/ovu/2ADKNnjpq7OjjoIttiSeqUDOrguYGcZNhKU34=|QcgJxBN6ea1Fbo3J0V8n3F9tUcAumfA3e01nDN+ihN8=", \ 29 | "passwordRevisionDate": null, \ 30 | "totp": null, \ 31 | "uris": [ \ 32 | { \ 33 | "match": null, \ 34 | "uri": "2.kS2d1arj/MM9h+mIW9RMAQ==|CNdUog9M8mByYXTFgkbYRg==|RC89j2K9sNcxqDf9f+aujnQm0LRNwXvqKQK0lIipDXQ=" \ 35 | }, \ 36 | { \ 37 | "match": null, \ 38 | "uri": "2.XnKvUBwgh4rVhlc2Kswqgg==|FCGHFqpj5jOWnS+SCmvF/A==|TPiRhI4mAZg05wEyXV7VdCbiQo0EVZ0BagDJrvxWcOw=" \ 39 | } \ 40 | ] \ 41 | },\ 42 | "fields": [\ 43 | {\ 44 | "type": 0,\ 45 | "name": "2.8cD6Lg0308EZTEgeiuvDhQ==|rbd5+MnoZmzm9ZGI2mB0iQzJ7HysVkQFXue48eAN0eA=|vyLz6vqsIFSHdW7xQmwzbg5jm2hsUb/pS/9aIYvS1Fs=",\ 46 | "value": "2.OEt4B5y21WB5tmkd6Gmk5w==|vXsHoRujWZj2OZNA9/iF5bIlBeWa0pI+ttr8/rgxAjA=|MZ/DDsntVddSFoY3mUPNe3JBUjCOc1ZK4PIEin9L0Oo="\ 47 | },\ 48 | {\ 49 | "type": 1,\ 50 | "name": "2.p0BEx6HRXvfA+0TeHFi4nA==|UW5dXnW4rlQocnHOTcLM/FOlQLbjQh/k+g65Yrh6COw=|jq42Sp0sgs6H+DyuLEDQ5UY7sbRj4DYMr8PAVD5G+OU=",\ 51 | "value": "2.si7K0uetUvT5BUAeFskx9Q==|4iKxRN3/6TUfhRWXGQijsaS3K7NTlE5v04WqhfeCcH8=|Dgo2TwZHRxeyLID/LkKBQIPvc5IJatbupFOiIc15K4E="\ 52 | },\ 53 | {\ 54 | "type": 2,\ 55 | "name": "2.49fH9DjGRS6RRTL4I9zZSg==|/k3uffKs1wQbdQU1oFnt6YbBHVtd/tl2XQQQbkPdtWM=|2vrIYiZnFhHk0hx0lNdIo8FkQDKJlmDRIDDpj9hyvhw=",\ 56 | "value": "2.53eXq9PhlhbUH1QASmZvKg==|djHCRO2WazzxcL2mjzxF5Q==|UVXokiiqBb/9rb/VQ+gOa6PpV0iifc1Ye5AhHMqClG0="\ 57 | },\ 58 | {\ 59 | "type": 2,\ 60 | "name": "2.QDn0bwKJbEgjWAATLJqWAg==|Csoq4Sr6O8byHZoiU70PwyBt9txNTN2Fjz2sl9ZD190=|nwzx3YGpgxk2Tu/bg0M8CEF+yHU4zhjfQOGxjSZVpUQ=",\ 61 | "value": "2.zGBCnWTtRfxuuwdr8MstVw==|RX24BmIJvcef9/A95Idbhg==|jr+Wp+kiBsvAp/HbsXRxr1WSqNDnyQATfdl9Y2nuTBU="\ 62 | }\ 63 | ]\ 64 | }' 65 | return dict( 66 | BW_SESSION='Tyy0rDgzvA/jgHsqUtKIgNnAWaRtHKZoSs6pa10qWQf0QmFtd2/xn8TNJy8Fu2nPRNVDpn3k7tu49W1pQVU8Zg==', 67 | cipher_response=json_loads(cipher_response), 68 | nl='\n', 69 | organization_id='1ff51ccd-0a25-46a2-a3cd-aa3000cfa874', 70 | protected_key='ArxoewBOPtCYZKqn34f8CoMQVUrNZnrhGU9OYuJu8UpB7DngEwf/TEHjbxPJJhUDG+DnPQR76J9d12/4tnGT5C6ZaLxxInRooT4AuX2ljIrSppCee1AvzIMu7ljGhR++ng==', 71 | protected_key_decoded=b'/lCGAMDGAq+mjRP3FJv+VNDDnbrYcVGnsiPeXTm4NfU=', 72 | test_database_filename='data.json', 73 | user_email='dev+bitwarden@mickaelperrin.fr', 74 | user_id='03780246-7f1d-4221-8615-aa3000cd8123', 75 | uuid_login_organization='fe6e74aa-a099-4cc1-ae8e-aa3000d02c14', 76 | uuid_login_personal='fd8870cc-3659-40aa-9492-aa3000cedbb3', 77 | uuid_note_personal='450cbad2-580b-4523-bce8-aa3000cf641a' 78 | ).get(item) 79 | 80 | 81 | @pytest.fixture 82 | def no_bw_session(monkeypatch): 83 | monkeypatch.setenv('BITWARDENCLI_APPDATA_DIR', path.dirname(__file__)) 84 | if environ.get('BW_SESSION'): 85 | monkeypatch.delenv('BW_SESSION') 86 | 87 | 88 | @pytest.fixture 89 | def bw_session(monkeypatch): 90 | monkeypatch.setenv('BW_SESSION', common_data('BW_SESSION')) 91 | monkeypatch.setenv('BITWARDENCLI_APPDATA_DIR', path.dirname(__file__)) 92 | 93 | 94 | @pytest.fixture 95 | def storage_service(): 96 | return StorageService(path.join(path.dirname(__file__), common_data('test_database_filename'))) 97 | 98 | 99 | @pytest.fixture() 100 | def secure_storage_service(): 101 | storage_service = StorageService(path.join(path.dirname(__file__), common_data('test_database_filename'))) 102 | return SecureStorageService(storage_service, CryptoService(storage_service)) 103 | 104 | 105 | @pytest.mark.usefixtures("bw_session") 106 | @pytest.fixture() 107 | def crypto_service(): 108 | storage_service = StorageService(path.join(path.dirname(__file__), common_data('test_database_filename'))) 109 | return CryptoService(storage_service) 110 | 111 | 112 | @pytest.fixture() 113 | def user_service(): 114 | storage_service = StorageService(path.join(path.dirname(__file__), common_data('test_database_filename'))) 115 | return UserService(storage_service) 116 | 117 | 118 | @pytest.fixture() 119 | def cipher_service(): 120 | storage_service = StorageService(path.join(path.dirname(__file__), common_data('test_database_filename'))) 121 | user_service = UserService(storage_service) 122 | return CipherService(storage_service, user_service) 123 | 124 | 125 | @pytest.fixture() 126 | def cipher_response(): 127 | return CipherResponse(common_data('cipher_response')) 128 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from bitwarden_simple_cli.__main__ import start 2 | 3 | if __name__ == '__main__': 4 | start() -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -r requirements/prod.txt -------------------------------------------------------------------------------- /requirements/common.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.24.0 2 | cffi==1.12.2 3 | cryptography==2.6.1 4 | pycparser==2.19 5 | -------------------------------------------------------------------------------- /requirements/dev.txt: -------------------------------------------------------------------------------- 1 | -r common.txt 2 | atomicwrites==1.3.0 3 | attrs==19.1.0 4 | coverage==4.5.3 5 | more-itertools==7.0.0 6 | pluggy==0.9.0 7 | pp-ez==0.2.0 8 | pprintpp==0.4.0 9 | py==1.8.0 10 | pytest==4.4.0 11 | pytest-cov==2.6.1 12 | six==1.12.0 -------------------------------------------------------------------------------- /requirements/prod.txt: -------------------------------------------------------------------------------- 1 | -r common.txt -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import io 5 | import os 6 | import sys 7 | from shutil import rmtree 8 | 9 | from setuptools import find_packages, setup, Command 10 | 11 | NAME = 'bitwarden simple cli' 12 | DESCRIPTION = 'Simple bitwarden CLI written in Python to list and decrypt secrets' 13 | URL = 'https://github.com/mickaelperrin/bitwarden-decrypt-cli' 14 | EMAIL = 'dev@mickaelperrin.fr' 15 | AUTHOR = 'Mickaël Perrin' 16 | REQUIRES_PYTHON = '>=3.7.0' 17 | VERSION = None 18 | EXTRAS = {} 19 | 20 | # ------------------------------------------------ 21 | here = os.path.abspath(os.path.dirname(__file__)) 22 | 23 | # Import the README and use it as the long-description. 24 | # Note: this will only work if 'README.md' is present in your MANIFEST.in file! 25 | try: 26 | with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: 27 | long_description = '\n' + f.read() 28 | except FileNotFoundError: 29 | long_description = DESCRIPTION 30 | 31 | try: 32 | with io.open(os.path.join(here, 'requirements', 'common.txt'), encoding='utf-8') as f: 33 | REQUIRED = f.read().splitlines() 34 | except FileNotFoundError: 35 | REQUIRED = [] 36 | 37 | # Load the package's __version__.py module as a dictionary. 38 | about = {} 39 | if not VERSION: 40 | project_slug = NAME.lower().replace("-", "_").replace(" ", "_") 41 | version_file_path = os.path.join(here, project_slug, '__version__.py') 42 | if not os.path.exists(version_file_path): 43 | raise Exception('Unable to find version file at path: %s' % version_file_path) 44 | with open(version_file_path) as f: 45 | exec(f.read(), about) 46 | else: 47 | about['__version__'] = VERSION 48 | 49 | 50 | class UploadCommand(Command): 51 | """Support setup.py upload.""" 52 | 53 | description = 'Build and publish the package.' 54 | user_options = [] 55 | 56 | @staticmethod 57 | def status(s): 58 | """Prints things in bold.""" 59 | print('\033[1m{0}\033[0m'.format(s)) 60 | 61 | def initialize_options(self): 62 | pass 63 | 64 | def finalize_options(self): 65 | pass 66 | 67 | def run(self): 68 | try: 69 | self.status('Removing previous builds…') 70 | rmtree(os.path.join(here, 'dist')) 71 | except OSError: 72 | pass 73 | 74 | self.status('Building Source and Wheel (universal) distribution…') 75 | os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) 76 | 77 | self.status('Uploading the package to PyPI via Twine…') 78 | os.system('twine upload dist/*') 79 | 80 | self.status('Pushing git tags…') 81 | os.system('git tag v{0}'.format(about['__version__'])) 82 | os.system('git push --tags') 83 | 84 | sys.exit() 85 | 86 | 87 | if not about['__version__']: 88 | raise Exception('Version is not set') 89 | 90 | # Where the magic happens: 91 | setup( 92 | name=NAME, 93 | version=about['__version__'], 94 | description=DESCRIPTION, 95 | long_description=long_description, 96 | long_description_content_type='text/markdown', 97 | keywords='bitwarden cli password secrets', 98 | author=AUTHOR, 99 | author_email=EMAIL, 100 | python_requires=REQUIRES_PYTHON, 101 | url=URL, 102 | packages=find_packages(exclude=["tests", "*.tests", "*.tests.*", "tests.*"]), 103 | # If your package is a single module, use this instead of 'packages': 104 | # py_modules=['mypackage'], 105 | entry_points={ 106 | 'console_scripts': ['bw-simple=bitwarden_simple_cli.__main__:start'], 107 | }, 108 | install_requires=REQUIRED, 109 | extras_require=EXTRAS, 110 | include_package_data=True, 111 | license='GPLv3', 112 | classifiers=[ 113 | # Trove classifiers 114 | # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 115 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 116 | 'Development Status :: 4 - Beta', 117 | 'Environment :: Console', 118 | 'Intended Audience :: Information Technology', 119 | 'Natural Language :: French', 120 | 'Topic :: Security', 121 | 'Topic :: Security :: Cryptography', 122 | 'Topic :: Utilities', 123 | 'Programming Language :: Python', 124 | 'Programming Language :: Python :: 3', 125 | 'Programming Language :: Python :: 3.7', 126 | 'Programming Language :: Python :: Implementation :: CPython', 127 | 'Programming Language :: Python :: Implementation :: PyPy' 128 | ], 129 | # $ setup.py publish support. 130 | cmdclass={ 131 | 'upload': UploadCommand, 132 | }, 133 | ) 134 | --------------------------------------------------------------------------------