├── .coveragerc ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── bin ├── create-vault-ca └── fetch-ssl-cert ├── debian ├── .gitignore ├── changelog ├── compat ├── control ├── rules └── source │ └── format ├── docs ├── Makefile ├── code.rst ├── conf.py ├── index.rst └── readme.rst ├── example ├── vault.hcl.init └── vault.hcl.ssl ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── fixtures │ ├── acomponent-test.test.org.key │ ├── acomponent-test.test.org.pem.empty │ ├── acomponent-test.test.org.pem.ko │ ├── acomponent-test.test.org.pem.ok │ └── acomponent.crt └── test_vault_ca.py └── vault_ca └── __init__.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | branch = True 3 | source = vault_ca 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | docs/_static/ 66 | docs/_templates/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # IPython Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # dotenv 81 | .env 82 | 83 | # virtualenv 84 | venv/ 85 | ENV/ 86 | 87 | # Spyder project settings 88 | .spyderproject 89 | 90 | # Rope project settings 91 | .ropeproject 92 | .pybuild/ 93 | 94 | # Debian packages 95 | debian/debhelper-build-stamp 96 | debian/*.debhelper 97 | debian/*.substvars 98 | debian/*.log 99 | debian/files 100 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "2.7" 5 | - "3.4" 6 | - "3.5" 7 | - "3.6" 8 | 9 | cache: pip 10 | 11 | install: 12 | - python setup.py build 13 | - python setup.py install 14 | - pip install pytest-cov requests-mock codecov codeclimate-test-reporter 15 | 16 | script: 17 | - py.test 18 | 19 | after_success: 20 | - codecov 21 | - CODECLIMATE_REPO_TOKEN=f8067bcd68e80313e77f6c8319cc79f4f3443e7d703fdc22acc4d1f71a927e6c codeclimate-test-reporter 22 | 23 | notifications: 24 | irc: 25 | channels: 26 | - "chat.freenode.net##crisidev" 27 | on_success: always # default: always 28 | on_failure: always # default: always 29 | use_notice: true 30 | -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vault CA 2 | [![Build Status](https://travis-ci.org/crisidev/vault-ca.svg?branch=master)](https://travis-ci.org/crisidev/vault-ca) [![codecov](https://codecov.io/gh/crisidev/vault-ca/branch/master/graph/badge.svg)](https://codecov.io/gh/crisidev/vault-ca) [![Code Climate](https://codeclimate.com/github/crisidev/vault-ca/badges/gpa.svg)](https://codeclimate.com/github/crisidev/vault-ca) [![Issue Count](https://codeclimate.com/github/crisidev/vault-ca/badges/issue_count.svg)](https://codeclimate.com/github/crisidev/vault-ca) [![Documentation Status](https://readthedocs.org/projects/vault-ca/badge/?version=latest)](http://vault-ca.readthedocs.io/en/latest/?badge=latest) 3 | 4 | Set of tools to create your own CA and manage certificates using hashicorp Vault. 5 | 6 | ## Install 7 | ```bash 8 | apt-get install libffi-dev libssl-dev 9 | pip install vault-ca 10 | ``` 11 | 12 | ## Documentation 13 | [https://vault-ca.readthedocs.io/en/latest/index.html](https://vault-ca.readthedocs.io/en/latest/index.html) 14 | 15 | ## How to 16 | ### Initialize the Vault 17 | Vault need to be initialized without SSL certificates and than switched. 18 | Once initialized and configured, fetch-ssl-cert can be used to retrieve 19 | Vault's own certificate/key pair and TLS can be switched on. 20 | 21 | Inside the the `example` folder you can find two different Vault server 22 | configurations for this purpose 23 | 24 | ```bash 25 | ❯❯❯ ~ vault server -config example/vault.hcl.init 26 | 27 | ❯❯❯ ~ export VAULT_ADDR="http://127.0.0.1:8200" 28 | 29 | ❯❯❯ ~ vault init 30 | Unseal Key 1: SmMc4xXT2oq6d7uJSnMMnuRKLh7EighJUeH4Kh/28naG 31 | Unseal Key 2: ovsPuWWd8dWVBqb+TPtqqQRjGPBNCor3rp1QLYYnhNZJ 32 | Unseal Key 3: XuASk26YBqQo9+cvi17Me5o7PWsQwVlL2hM8G1bjOyIs 33 | Unseal Key 4: NwhxHrkByuVfP4GURwDc/tZ1qPP6bVsmP2hUIQj+nvBN 34 | Unseal Key 5: 0Kfq2jVlE2Db8Nj5mIXVhQTRONYz/0qZ1zm1BObUO4nx 35 | Initial Root Token: 087efd94-3680-0ff4-25b7-a92177cd3c46 36 | 37 | Vault initialized with 5 keys and a key threshold of 3. Please 38 | securely distribute the above keys. When the vault is re-sealed, 39 | restarted, or stopped, you must provide at least 3 of these keys 40 | to unseal it again. 41 | 42 | Vault does not store the master key. Without at least 3 keys, 43 | your vault will remain permanently sealed. 44 | 45 | ❯❯❯ ~ vault unseal SmMc4xXT2oq6d7uJSnMMnuRKLh7EighJUeH4Kh/28naG 46 | Sealed: true 47 | Key Shares: 5 48 | Key Threshold: 3 49 | Unseal Progress: 1 50 | Unseal Nonce: 4ba54ac9-d60b-4078-05da-285ef05bf303 51 | ❯❯❯ ~ vault unseal ovsPuWWd8dWVBqb+TPtqqQRjGPBNCor3rp1QLYYnhNZJ 52 | Sealed: true 53 | Key Shares: 5 54 | Key Threshold: 3 55 | Unseal Progress: 2 56 | Unseal Nonce: 4ba54ac9-d60b-4078-05da-285ef05bf303 57 | ❯❯❯ ~ vault unseal XuASk26YBqQo9+cvi17Me5o7PWsQwVlL2hM8G1bjOyIs 58 | Sealed: false 59 | Key Shares: 5 60 | Key Threshold: 3 61 | Unseal Progress: 0 62 | Unseal Nonce: 63 | 64 | ❯❯❯ ~ vault status 65 | Sealed: false 66 | Key Shares: 5 67 | Key Threshold: 3 68 | Unseal Progress: 0 69 | Unseal Nonce: 70 | Version: 0.7.2 71 | Cluster Name: test-cluster 72 | Cluster ID: 8f948916-8a3d-b220-f0b4-7c5bb74dc5a6 73 | 74 | High-Availability Enabled: false 75 | ``` 76 | 77 | ### Intialize certificate authority 78 | After initializing and unsealing the Vault, you need to create the certificate authority. 79 | 80 | One of the script installed by **vault_ca**, `create-vault-ca`, will do than for you. 81 | 82 | Default parameters: 83 | 84 | * The script creates a certificate authority valid for 5 years. 85 | * Certificates have a maximum TTL of 5 years and a default one of 30 days. 86 | * Authorization tokens have a maximum TTL of 5 years and a default one of 1 year. 87 | 88 | All the parameters above can be configured through command line arguments. See `create-vault-ca --help` for details. 89 | 90 | NOTE: set `--vault-token` option using `Initial Root Token` from above. 91 | 92 | ```bash 93 | ❯❯❯ ~ create-vault-ca --domain=test.org --component=test --vault-addr="http://127.0.0.1:8200" --vault-token=087efd94-3680-0ff4-25b7-a92177cd3c46 94 | Are you sure this script have not been already run on this vault? It can break / override configs [y|N] y 95 | Successfully mounted 'pki' at 'pki/test.org'! 96 | Successfully tuned mount 'pki/test.org'! 97 | Key Value 98 | --- ----- 99 | certificate -----BEGIN CERTIFICATE----- 100 | MIIC9jCCAd6gAwIBAgIUKybrEs7kUvRSgepQuImxonoznCwwDQYJKoZIhvcNAQEL 101 | BQAwEzERMA8GA1UEAxMIdGVzdC5vcmcwHhcNMTcwNTE0MTcyNDMwWhcNMjIwNTEz 102 | MTcyNTAwWjATMREwDwYDVQQDEwh0ZXN0Lm9yZzCCASIwDQYJKoZIhvcNAQEBBQAD 103 | ggEPADCCAQoCggEBALeVV8zUKwhYJz0eVg+6rWfCPz+GdxxIXeiChULAU+zHWvDf 104 | Jxye9JrcTdc/XUI0ZSw33F2JEjLkDasdchfL4ESRbUTdnJj1kYW6KEF9X3rhL/AM 105 | hdX+EqUQ9yvXRlvcSyGObVD7ayRUcG2IDpCLRuFW5bkw+MxvSjyzIf6+W3bs5DVz 106 | mFKqRv5Y3ycsuzc8CiDjxj/1LZWvBfqUFf8jePO0bzL3kw7uViZA4fJ23wPLqTyq 107 | IRX52ODZFC3SeyF600lerCLGY4Bgol8YtZwjsx+MxpPnszlkitxT2wjAghfPTV0W 108 | 8BebQi4D+CN4A4C6joyGZrdagzsUF3LoeGoDFh8CAwEAAaNCMEAwDgYDVR0PAQH/ 109 | BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHovOm1ZHkAsmCGKn+u3 110 | QmlCrriZMA0GCSqGSIb3DQEBCwUAA4IBAQBgDE//Tktbe16VSSrqP8MNYGtMG+jZ 111 | PV2Ao7FCrgSPwjBQHPXR1fh+g4MMG4S9iI8QtXIz49/ZYXfXPU6LPq8W/zrIlf/g 112 | 7PODdOo/w7LA7CBHG6ceQtRXHuaMJvJ8EybTQ4vc7LK2FMdEZbBQQkQfnCunR8bz 113 | oACVTooX2DkSPHCM24XSBsmMsHxImEYrjzsr0RyU+R9Tq+rdhjoEyUzQxklIecTq 114 | 8D1yfIrgIfYfT1qf6n2bEb+xIfk47v8yXlIUS3KLDadUtqybHIzsbSKEwiQse7rF 115 | AOoUPGoZMSJAr52y0SW2QE8mJoGyX0HeqeX2ocrKw3WvwXF1oHpOB6Au 116 | -----END CERTIFICATE----- 117 | expiration 1652462700 118 | issuing_ca -----BEGIN CERTIFICATE----- 119 | MIIC9jCCAd6gAwIBAgIUKybrEs7kUvRSgepQuImxonoznCwwDQYJKoZIhvcNAQEL 120 | BQAwEzERMA8GA1UEAxMIdGVzdC5vcmcwHhcNMTcwNTE0MTcyNDMwWhcNMjIwNTEz 121 | MTcyNTAwWjATMREwDwYDVQQDEwh0ZXN0Lm9yZzCCASIwDQYJKoZIhvcNAQEBBQAD 122 | ggEPADCCAQoCggEBALeVV8zUKwhYJz0eVg+6rWfCPz+GdxxIXeiChULAU+zHWvDf 123 | Jxye9JrcTdc/XUI0ZSw33F2JEjLkDasdchfL4ESRbUTdnJj1kYW6KEF9X3rhL/AM 124 | hdX+EqUQ9yvXRlvcSyGObVD7ayRUcG2IDpCLRuFW5bkw+MxvSjyzIf6+W3bs5DVz 125 | mFKqRv5Y3ycsuzc8CiDjxj/1LZWvBfqUFf8jePO0bzL3kw7uViZA4fJ23wPLqTyq 126 | IRX52ODZFC3SeyF600lerCLGY4Bgol8YtZwjsx+MxpPnszlkitxT2wjAghfPTV0W 127 | 8BebQi4D+CN4A4C6joyGZrdagzsUF3LoeGoDFh8CAwEAAaNCMEAwDgYDVR0PAQH/ 128 | BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHovOm1ZHkAsmCGKn+u3 129 | QmlCrriZMA0GCSqGSIb3DQEBCwUAA4IBAQBgDE//Tktbe16VSSrqP8MNYGtMG+jZ 130 | PV2Ao7FCrgSPwjBQHPXR1fh+g4MMG4S9iI8QtXIz49/ZYXfXPU6LPq8W/zrIlf/g 131 | 7PODdOo/w7LA7CBHG6ceQtRXHuaMJvJ8EybTQ4vc7LK2FMdEZbBQQkQfnCunR8bz 132 | oACVTooX2DkSPHCM24XSBsmMsHxImEYrjzsr0RyU+R9Tq+rdhjoEyUzQxklIecTq 133 | 8D1yfIrgIfYfT1qf6n2bEb+xIfk47v8yXlIUS3KLDadUtqybHIzsbSKEwiQse7rF 134 | AOoUPGoZMSJAr52y0SW2QE8mJoGyX0HeqeX2ocrKw3WvwXF1oHpOB6Au 135 | -----END CERTIFICATE----- 136 | serial_number 2b:26:eb:12:ce:e4:52:f4:52:81:ea:50:b8:89:b1:a2:7a:33:9c:2c 137 | 138 | Success! Data written to: pki/test.org/roles/cert 139 | Policy 'pki/test.org/cert' written. 140 | Success! Data written to: auth/token/roles/services 141 | Success! Data written to: auth/token/roles/users 142 | 143 | Generating services token (REMEMBER TO SAVE IT) 144 | Key Value 145 | --- ----- 146 | token 9a6b0ee1-c159-3710-dc3f-7641a5ef9222 147 | token_accessor 3730bbec-d8ae-eac0-cc26-c4fb6efa3e0a 148 | token_duration 8760h0m0s 149 | token_renewable true 150 | token_policies [default pki/test.org/cert] 151 | 152 | Have you saved the services token above? [y|N] y 153 | 154 | Generating users token (REMEMBER TO SAVE IT) 155 | Key Value 156 | --- ----- 157 | token 3f2ebc35-1793-dc9e-f8da-f6dd6d081ca2 158 | token_accessor 7fcf4113-4918-54a1-d24c-8533b3b10e53 159 | token_duration 8760h0m0s 160 | token_renewable true 161 | token_policies [default pki/test.org/cert] 162 | 163 | Have you saved the users token above? [y|N] y 164 | 165 | To boostrap the CA use "fetch-ssl-cert -c test -n -t -b -o " 166 | To create / renew a certificate use "fetch-ssl-cert -c test -n -t -o " 167 | ``` 168 | 169 | From now on, you can use one of the two tokens created during the CA setup: 170 | 171 | * services: used by automated services to fetch certificate/key pairs. 172 | * users: used by humans to fetch certificate/key pairs. 173 | 174 | ### Secure Vault with TLS 175 | Once the CA is setup, Vault itself need to get its own certificate/key pair and the CA need to be downloaded and bootstrapped into the system. 176 | 177 | I am assuming you are on Debian and you have `update-ca-certificates` available. 178 | 179 | NOTE: from now on the token used is `services` from above. 180 | 181 | ```bash 182 | ❯❯❯ fetch-ssl-cert -c test -n vault.test.org -d test.org -i 127.0.0.1 -t 9a6b0ee1-c159-3710-dc3f-7641a5ef9222 -b -A http://127.0.0.1:8200 -D 183 | 2017-05-14 18:52:58,443 __init__.py:44 DEBUG:vault address is `http://127.0.0.1:8200` 184 | 2017-05-14 18:52:58,443 __init__.py:174 DEBUG:request url is `http://127.0.0.1:8200/v1/pki/test.org/issue/cert` 185 | 2017-05-14 18:52:58,443 __init__.py:131 DEBUG:requesting new cert / key part for CA domain: `test.org`, component: `test`, common_name: `vault.test.org`, ip_sans: `127.0.0.1`, alt_names: `None`, ttl: `8760h` 186 | 2017-05-14 18:52:58,450 connectionpool.py:207 DEBUG:Starting new HTTP connection (1): 127.0.0.1 187 | 2017-05-14 18:52:58,590 connectionpool.py:395 DEBUG:http://127.0.0.1:8200 "PUT /v1/pki/test.org/issue/cert HTTP/1.1" 200 None 188 | 2017-05-14 18:52:58,591 __init__.py:59 DEBUG:directory `/usr/local/share/ca-certificates/test.org` already exists, skipping creation 189 | 2017-05-14 18:52:58,591 __init__.py:106 DEBUG:writing certificate for vault.test.org on /usr/local/share/ca-certificates/test.org/test-vault.test.org.pem 190 | 2017-05-14 18:52:58,591 __init__.py:109 DEBUG:writing private key for vault.test.org on /usr/local/share/ca-certificates/test.org/test-vault.test.org.key 191 | 2017-05-14 18:52:58,591 __init__.py:114 DEBUG:writing CA on /usr/local/share/ca-certificates/test.org/test.crt 192 | ``` 193 | 194 | Now that the certificate/key pair and the CA are saved on the disk, we need to update the system certificate authorities 195 | 196 | ```bash 197 | ❯❯❯ update-ca-certificates --fresh 198 | Updating certificates in /etc/ssl/certs... 1 added, 0 removed; done. 199 | Running hooks in /etc/ca-certificates/update.d....done. 200 | ``` 201 | 202 | Stop vault and restart it using the other configuration from `example` directory and repeat the unseal process. 203 | 204 | ```bash 205 | ❯❯❯ vault server -config example/vault.hcl.ssl 206 | ``` 207 | 208 | Now vault is fully secure and usable. 209 | 210 | NOTE: remember to register a local DNS for `vault.test.org` or use the command line option to specify the Vault address. 211 | 212 | ### Fetch certificate/key pair 213 | Let's fetch a certificate/key pair for a test domain. 214 | 215 | ```bash 216 | fetch-ssl-cert -c test -n test.test.org -d test.org -t 9a6b0ee1-c159-3710-dc3f-7641a5ef9222 -A https://127.0.0.1:8200 -D 217 | 2017-05-14 18:52:58,443 __init__.py:44 DEBUG:vault address is `https://127.0.0.1:8200` 218 | 2017-05-14 18:52:58,443 __init__.py:174 DEBUG:request url is `https://127.0.0.1:8200/v1/pki/test.org/issue/cert` 219 | 2017-05-14 18:52:58,443 __init__.py:131 DEBUG:requesting new cert / key part for CA domain: `test.org`, component: `test`, common_name: `test.test.org`, ip_sans: `None`, alt_names: `None`, ttl: `8760h` 220 | 2017-05-14 18:52:58,450 connectionpool.py:207 DEBUG:Starting new HTTPS connection (1): 127.0.0.1 221 | 2017-05-14 18:52:58,590 connectionpool.py:395 DEBUG:https://127.0.0.1:8200 "PUT /v1/pki/test.org/issue/cert HTTP/1.1" 200 None 222 | 2017-05-14 18:52:58,591 __init__.py:59 DEBUG:directory `/usr/local/share/ca-certificates/test.org` already exists, skipping creation 223 | 2017-05-14 18:52:58,591 __init__.py:106 DEBUG:writing certificate for test.test.org on /usr/local/share/ca-certificates/test.org/test-test.test.org.pem 224 | 2017-05-14 18:52:58,591 __init__.py:109 DEBUG:writing private key for vault.test.org on /usr/local/share/ca-certificates/test.org/test-test.test.org.key 225 | ``` 226 | -------------------------------------------------------------------------------- /bin/create-vault-ca: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | function usage { 6 | cat << EOT 7 | usage: create-vault-ca --domain=DOMAIN --component=COMPONENT 8 | --vault-addr=VAULT_ADDR --vault-token=VAULT_TOKEN 9 | [--cert-max-ttl=CERT_MAX_TTL] [--cert-ttl=CERT_TTL] 10 | [--token-max-ttl=TOKEN_MAX_TTL] [--token-ttl=TOKEN_TTL] 11 | [--ca-ttl=CA_TTL] [-h/--help] 12 | 13 | Create a new CA for a component on the Vault. 14 | A component is be a service which need to use certs auth. 15 | 16 | The Vault need to be unsealed and initialized to be able to run the script. 17 | 18 | NOTE: all TTLs need to be specified as number of hours, like 24h (remember the final h). 19 | 20 | Documentation: https://github.com/crisidev/vault-ca/blob/master/README.md 21 | 22 | mandatory arguments: 23 | --component=COMPONENT, -c=COMPONENT 24 | Component used 25 | --domain=DOMAIN, -d=DOMAIN 26 | CA domain 27 | --vault-addr=VAULT_ADDR, -a=VAULT_ADDR 28 | Vault admin token 29 | --vault-token=VAULT_TOKEN, -v=VAULT_TOKEN 30 | Vault admin token 31 | 32 | optional arguments: 33 | -h, --help Show this help message and exit 34 | --cert-max-ttl=CERT_MAX_TTL, -C=CERT_MAX_TTL 35 | Max TTL for a new certificate, in hours, default to 43800h (5 years) 36 | --cert-ttl=CERT_TTL, -c=CERT_TTL 37 | Default TTL for a new certificate, in hours, default to 730h (1 month) 38 | --token-max-ttl=TOKEN_MAX_TTL, -T=TOKEN_MAX_TTL 39 | Max TTL for an authentication token, in hours, default to 43800h (5 years) 40 | --token-ttl=TOKEN_TTL, -t=TOKEN_TTL 41 | Default TTL for an authentication token, in hours, default to 8760h (1 year) 42 | --ca-ttl=CA_TTL, -C=CA_TTL 43 | TTL for the root CA, in hours, default to 43800h (5 years) 44 | EOT 45 | } 46 | 47 | # parse command line arguments 48 | while [ "$1" != "" ]; do 49 | PARAM="$(echo "$1" | awk -F= '{print $1}')" 50 | # shellcheck disable=SC2001 51 | VALUE="$(echo "$1" | sed 's/^[^=]*=//g')" 52 | case ${PARAM} in 53 | "-h" | "--help") 54 | usage 55 | exit 0 56 | ;; 57 | "-d" | "--domain") 58 | DOMAIN=${VALUE} 59 | ;; 60 | "-c" | "--component") 61 | COMPONENT=${VALUE} 62 | ;; 63 | "-a" | "--vault-addr") 64 | VAULT_ADDR=${VALUE} 65 | ;; 66 | "-v" | "--vault-token") 67 | VAULT_TOKEN=${VALUE} 68 | ;; 69 | "-P" | "--cert-max-ttl") 70 | CERT_MAX_TTL=${VALUE} 71 | ;; 72 | "-p" | "--cert-ttl") 73 | CERT_TTL=${VALUE} 74 | ;; 75 | "-T" | "--token-max-ttl") 76 | TOKEN_MAX_TTL=${VALUE} 77 | ;; 78 | "-t" | "--token-ttl") 79 | TOKEN_TTL=${VALUE} 80 | ;; 81 | "-C" | "--ca-ttl") 82 | CA_TTL=${VALUE} 83 | ;; 84 | *) 85 | echo "ERROR: unknown parameter \"$PARAM\"" 86 | echo 87 | usage 88 | exit 1 89 | ;; 90 | esac 91 | shift 92 | done 93 | 94 | # check mandatory arguments 95 | if [ -z "${DOMAIN}" ] || [ -z "${COMPONENT}" ] || [ -z "${VAULT_TOKEN}" ] || [ -z "${VAULT_ADDR}" ]; then 96 | usage 97 | exit 1 98 | fi 99 | 100 | export VAULT_TOKEN 101 | export VAULT_ADDR 102 | 103 | # max ttls 104 | CERT_MAX_TTL=${CERT_MAX_TTL:-43800h} # 5 years 105 | TOKEN_MAX_TTL=${TOKEN_MAX_TTL:-43800h} # 5 years 106 | 107 | # default ttls 108 | CA_TTL=${CA_TTL:-43800h} # 5 years 109 | CERT_TTL=${CERT_TTL:-730h} # 1 month 110 | TOKEN_TTL=${TOKEN_TTL:-8760h} # 1 year 111 | 112 | # vault ca path 113 | CA_PATH=pki/${DOMAIN} 114 | 115 | function read_yes_no { 116 | MESSAGE=$1 117 | echo -n "${MESSAGE} " 118 | read -r answer 119 | if ! echo "$answer" | grep -iq "^y" ;then 120 | echo "exiting." 121 | exit 1 122 | fi 123 | } 124 | 125 | function mount_pki { 126 | # mount vault path for this CA and tune expiration to $MAX_TTL 127 | vault mount -path "${CA_PATH}" pki 128 | vault mount-tune -max-lease-ttl="${CA_TTL}" "${CA_PATH}" 129 | } 130 | 131 | function generate_root_ca { 132 | # generate root CA 133 | vault write "${CA_PATH}"/root/generate/internal common_name="${DOMAIN}" exclude_cn_from_sans=true ttl="${CA_TTL}" 134 | } 135 | 136 | function generate_cert_role { 137 | # create a role name "cert" able to generate certificates 138 | vault write "${CA_PATH}"/roles/cert \ 139 | allow_any_name=true allow_bare_domains=true \ 140 | allow_subdomains=true allow_glob_domains=true \ 141 | allow_localhost=true allow_ip_sans=true \ 142 | ou="${COMPONENT}" organization="${DOMAIN}" \ 143 | ttl="${CERT_TTL}" max_ttl="${CERT_MAX_TTL}" 144 | } 145 | 146 | function generate_cert_policy { 147 | # policy for to allow access only to token releated to $COMPONENT 148 | cat < -t -b -o \"" 192 | echo "To create / renew a certificate use \"fetch-ssl-cert -c ${COMPONENT} -n -t -o \"" 193 | } 194 | 195 | read_yes_no "Are you sure this script have not been already run on this vault? It can break / override configs [y|N]" 196 | 197 | mount_pki 198 | generate_root_ca 199 | generate_cert_role 200 | generate_cert_policy 201 | configure_services_token 202 | configure_users_token 203 | generate_services_token 204 | generate_users_token 205 | print_fetching_info 206 | 207 | exit 0 208 | -------------------------------------------------------------------------------- /bin/fetch-ssl-cert: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | import logging 5 | import argparse 6 | 7 | from vault_ca import VaultCA, VaultCAError, VERSION 8 | 9 | 10 | def parse_args(): 11 | parser = argparse.ArgumentParser( 12 | description="""Fetch a certificate/key pair from the Vault. 13 | Documentation: https://github.com/crisidev/vault-ca/blob/master/README.md""" 14 | ) 15 | 16 | # required 17 | parser.add_argument('--component', '-c', dest='component', required=True, help="Component used") 18 | parser.add_argument('--domain', '-d', dest='domain', required=True, help="CA domain") 19 | parser.add_argument('--token', '-t', dest='vault_token', required=True, help="Vault token for this component") 20 | parser.add_argument('--common-name', '-n', dest='common_name', required=True, help="Common Name (CN)") 21 | 22 | # optional 23 | parser.add_argument( 24 | '--alt-names', '-a', dest='alt_names', required=False, help="Alternative names (optional, comma sepatated)" 25 | ) 26 | parser.add_argument( 27 | '--ip-san', '-i', dest='ip_sans', required=False, help="IP addresses list (optional, comma separated)" 28 | ) 29 | parser.add_argument('--ttl', '-T', dest='ttl', default="8760h", help="Certificate TTL in hours (default 1 year)") 30 | parser.add_argument('--vault-address', '-A', dest='vault_address', required=False, help="Vault server URL") 31 | parser.add_argument( 32 | '--no-ssl-verify', 33 | '-V', 34 | dest='ssl_verify', 35 | action="store_false", 36 | default=True, 37 | help="Disable SSL verification (implied by -b)" 38 | ) 39 | parser.add_argument( 40 | '--bootstrap-ca', 41 | '-b', 42 | dest='bootstrap_ca', 43 | action="store_true", 44 | default=False, 45 | help="Be the first to call vault to fetch the CA file (implies -V)" 46 | ) 47 | parser.add_argument( 48 | '--output-dir', '-o', dest='output_dir', required=False, help="Certificate / keys pair output directory" 49 | ) 50 | parser.add_argument('--ca-path', '-C', dest='ca_path', required=False, help="CA output directory") 51 | parser.add_argument('--debug', '-D', dest='debug', action="store_true", help="Enable debug") 52 | parser.add_argument('--version', action='version', version="{}".format(VERSION)) 53 | 54 | return parser.parse_args() 55 | 56 | 57 | def main(): 58 | args = parse_args() 59 | print(args.ssl_verify) 60 | logging.basicConfig( 61 | level=logging.DEBUG if args.debug else logging.INFO, 62 | format='%(asctime)s %(filename)s:%(lineno)s %(levelname)s:%(message)s' 63 | ) 64 | try: 65 | ca = VaultCA(vars(args)) 66 | ca.fetch(args.common_name, ip_sans=args.ip_sans, alt_names=args.alt_names, ttl=args.ttl) 67 | except VaultCAError as e: 68 | logging.error(e) 69 | sys.exit(1) 70 | except Exception as e: 71 | logging.exception(e) 72 | sys.exit(2) 73 | else: 74 | sys.exit(0) 75 | 76 | 77 | if __name__ == '__main__': 78 | main() 79 | -------------------------------------------------------------------------------- /debian/.gitignore: -------------------------------------------------------------------------------- 1 | python3-vault-ca 2 | python-vault-ca 3 | -------------------------------------------------------------------------------- /debian/changelog: -------------------------------------------------------------------------------- 1 | vault-ca (0.6-1) unstable; urgency=medium 2 | 3 | * New upstream version 4 | 5 | -- Matteo Bigoi Wed, 05 Jul 2017 00:20:40 +0100 6 | 7 | vault-ca (0.5-2.1) unstable; urgency=medium 8 | 9 | * Fix bootstrap argument parsing. 10 | 11 | -- Matteo Bigoi Wed, 05 Jul 2017 00:02:23 +0100 12 | 13 | vault-ca (0.5-2) unstable; urgency=low 14 | 15 | * update package support only python2 and python3 16 | 17 | -- Matteo Bigoi Tue, 20 Jun 2017 19:53:31 +0000 18 | 19 | vault-ca (0.5-1) unstable; urgency=low 20 | 21 | * source package automatically created by stdeb 0.8.2 22 | 23 | -- Matteo Bigoi Tue, 06 Jun 2017 20:06:08 +0000 24 | -------------------------------------------------------------------------------- /debian/compat: -------------------------------------------------------------------------------- 1 | 9 2 | -------------------------------------------------------------------------------- /debian/control: -------------------------------------------------------------------------------- 1 | Source: vault-ca 2 | Maintainer: Matteo Bigoi 3 | Section: python 4 | Priority: optional 5 | Build-Depends: debhelper (>= 9), dh-python (>= 2), 6 | python-setuptools (>= 33.1), python-all (>= 2.7), python-pytest-runner (>= 2.7), python-requests (>= 2.4), python-openssl (>= 16.2), python-pytest (>= 3.0), python-pytest-cov (>= 2.4), python-requests-mock (>= 1.0), 7 | python3-setuptools (>= 0.6b3), python3-all (>= 3.4), python3-pytest-runner (>= 2.7), python3-requests (>= 2.4), python3-openssl (>= 16.2), python3-pytest (>= 3.0.6), python3-pytest-cov (>= 2.4), python3-requests-mock (>= 1.0) 8 | Standards-Version: 3.9.1 9 | X-Python-Version: >= 2.7 10 | X-Python3-Version: >= 3.4 11 | 12 | Package: python3-vault-ca 13 | Architecture: all 14 | Depends: ${misc:Depends}, ${python3:Depends}, python3-all (>= 3.4), python3-requests (>= 2.4), python3-openssl (>= 16.2) 15 | Description: Set of utils (python3) to create your own CA using hashicorp Vault 16 | 17 | Package: python-vault-ca 18 | Architecture: all 19 | Depends: ${misc:Depends}, ${python:Depends}, python-all (>= 2.7), python-requests (>= 2.4), python-openssl (>= 16.2) 20 | Description: Set of utils (python2) to create your own CA using hashicorp Vault 21 | 22 | -------------------------------------------------------------------------------- /debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | export PYBUILD_NAME=vault-ca 3 | %: 4 | dh $@ --with python2,python3 --buildsystem=pybuild 5 | 6 | -------------------------------------------------------------------------------- /debian/source/format: -------------------------------------------------------------------------------- 1 | 3.0 (quilt) 2 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = vault-ca 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/code.rst: -------------------------------------------------------------------------------- 1 | API documentation 2 | ================== 3 | 4 | This is the vault-ca API documentation. It contains the documentation extracted from the docstrings of the various classes, methods, and functions in the vault-ca package. If you want to know what a certain function/method does, this is the place to look. 5 | 6 | .. contents:: 7 | :depth: 2 8 | 9 | :mod:`vault_ca` Module 10 | ~~~~~~~~~~~~~~~~~~~~~~ 11 | 12 | `Source 13 | 14 | .. autoclass:: vault_ca.VaultCA 15 | :members: 16 | 17 | .. autoexception:: vault_ca.VaultCAError 18 | :members: 19 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # vault-ca documentation build configuration file, created by 5 | # sphinx-quickstart on Mon May 15 16:59:13 2017. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | import os 21 | import sys 22 | sys.path.insert(0, os.path.abspath('..')) 23 | 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # 29 | # needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | extensions = [ 35 | 'sphinx.ext.autodoc' 36 | ] 37 | 38 | # Add any paths that contain templates here, relative to this directory. 39 | templates_path = ['_templates'] 40 | 41 | # The suffix(es) of source filenames. 42 | # You can specify multiple suffix as a list of string: 43 | # 44 | source_suffix = '.rst' 45 | 46 | # The master toctree document. 47 | master_doc = 'index' 48 | 49 | # General information about the project. 50 | project = 'vault-ca' 51 | copyright = '2017, Matteo Bigoi' 52 | author = 'Matteo Bigoi' 53 | 54 | # The version info for the project you're documenting, acts as replacement for 55 | # |version| and |release|, also used in various other places throughout the 56 | # built documents. 57 | # 58 | # The short X.Y version. 59 | version = '0.6' 60 | # The full version, including alpha/beta/rc tags. 61 | release = 'alpha' 62 | 63 | # The language for content autogenerated by Sphinx. Refer to documentation 64 | # for a list of supported languages. 65 | # 66 | # This is also used if you do content translation via gettext catalogs. 67 | # Usually you set "language" from the command line for these cases. 68 | language = None 69 | 70 | # List of patterns, relative to source directory, that match files and 71 | # directories to ignore when looking for source files. 72 | # This patterns also effect to html_static_path and html_extra_path 73 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 74 | 75 | # The name of the Pygments (syntax highlighting) style to use. 76 | pygments_style = 'sphinx' 77 | 78 | # If true, `todo` and `todoList` produce output, else they produce nothing. 79 | todo_include_todos = True 80 | 81 | 82 | # -- Options for HTML output ---------------------------------------------- 83 | 84 | # The theme to use for HTML and HTML Help pages. See the documentation for 85 | # a list of builtin themes. 86 | # 87 | html_theme = 'default' 88 | 89 | # Theme options are theme-specific and customize the look and feel of a theme 90 | # further. For a list of options available for each theme, see the 91 | # documentation. 92 | # 93 | # html_theme_options = {} 94 | 95 | # Add any paths that contain custom static files (such as style sheets) here, 96 | # relative to this directory. They are copied after the builtin static files, 97 | # so a file named "default.css" will overwrite the builtin "default.css". 98 | html_static_path = ['_static'] 99 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. vault-ca documentation master file, created by 2 | sphinx-quickstart on Mon May 15 16:59:13 2017. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to vault-ca's documentation! 7 | ==================================== 8 | 9 | .. toctree:: 10 | :maxdepth: 5 11 | :caption: Index: 12 | 13 | readme 14 | code 15 | 16 | Indices and tables 17 | ================== 18 | 19 | * :ref:`genindex` 20 | * :ref:`modindex` 21 | * :ref:`search` 22 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | Vault CA 2 | ======== 3 | 4 | |Build Status| |codecov| |Code Climate| |Issue Count| 5 | 6 | Set of tools to create your own CA and manage certificates using 7 | hashicorp Vault. 8 | 9 | Install 10 | ------- 11 | 12 | .. code:: bash 13 | 14 | apt-get install libffi-dev libssl-dev 15 | pip install vault-ca 16 | 17 | How to 18 | ------ 19 | 20 | Initialize the Vault 21 | ~~~~~~~~~~~~~~~~~~~~ 22 | 23 | Vault need to be initialized without SSL certificates and than switched. 24 | Once initialized and configured, fetch-ssl-cert can be used to retrieve 25 | Vault's own certificate/key pair and TLS can be switched on. 26 | 27 | Inside the the ``example`` folder you can find two different Vault 28 | server configurations for this purpose 29 | 30 | .. code:: bash 31 | 32 | ❯❯❯ ~ vault server -config example/vault.hcl.init 33 | 34 | ❯❯❯ ~ export VAULT_ADDR="http://127.0.0.1:8200" 35 | 36 | ❯❯❯ ~ vault init 37 | Unseal Key 1: SmMc4xXT2oq6d7uJSnMMnuRKLh7EighJUeH4Kh/28naG 38 | Unseal Key 2: ovsPuWWd8dWVBqb+TPtqqQRjGPBNCor3rp1QLYYnhNZJ 39 | Unseal Key 3: XuASk26YBqQo9+cvi17Me5o7PWsQwVlL2hM8G1bjOyIs 40 | Unseal Key 4: NwhxHrkByuVfP4GURwDc/tZ1qPP6bVsmP2hUIQj+nvBN 41 | Unseal Key 5: 0Kfq2jVlE2Db8Nj5mIXVhQTRONYz/0qZ1zm1BObUO4nx 42 | Initial Root Token: 087efd94-3680-0ff4-25b7-a92177cd3c46 43 | 44 | Vault initialized with 5 keys and a key threshold of 3. Please 45 | securely distribute the above keys. When the vault is re-sealed, 46 | restarted, or stopped, you must provide at least 3 of these keys 47 | to unseal it again. 48 | 49 | Vault does not store the master key. Without at least 3 keys, 50 | your vault will remain permanently sealed. 51 | 52 | ❯❯❯ ~ vault unseal SmMc4xXT2oq6d7uJSnMMnuRKLh7EighJUeH4Kh/28naG 53 | Sealed: true 54 | Key Shares: 5 55 | Key Threshold: 3 56 | Unseal Progress: 1 57 | Unseal Nonce: 4ba54ac9-d60b-4078-05da-285ef05bf303 58 | ❯❯❯ ~ vault unseal ovsPuWWd8dWVBqb+TPtqqQRjGPBNCor3rp1QLYYnhNZJ 59 | Sealed: true 60 | Key Shares: 5 61 | Key Threshold: 3 62 | Unseal Progress: 2 63 | Unseal Nonce: 4ba54ac9-d60b-4078-05da-285ef05bf303 64 | ❯❯❯ ~ vault unseal XuASk26YBqQo9+cvi17Me5o7PWsQwVlL2hM8G1bjOyIs 65 | Sealed: false 66 | Key Shares: 5 67 | Key Threshold: 3 68 | Unseal Progress: 0 69 | Unseal Nonce: 70 | 71 | ❯❯❯ ~ vault status 72 | Sealed: false 73 | Key Shares: 5 74 | Key Threshold: 3 75 | Unseal Progress: 0 76 | Unseal Nonce: 77 | Version: 0.7.2 78 | Cluster Name: test-cluster 79 | Cluster ID: 8f948916-8a3d-b220-f0b4-7c5bb74dc5a6 80 | 81 | High-Availability Enabled: false 82 | 83 | Intialize certificate authority 84 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 85 | 86 | After initializing and unsealing the Vault, you need to create the 87 | certificate authority. 88 | 89 | One of the script installed by **vault\_ca**, ``create-vault-ca``, will 90 | do than for you. 91 | 92 | Default parameters: 93 | 94 | - The script creates a certificate authority valid for 5 years. 95 | - Certificates have a maximum TTL of 5 years and a default one of 30 96 | days. 97 | - Authorization tokens have a maximum TTL of 5 years and a default one 98 | of 1 year. 99 | 100 | All the parameters above can be configured through command line 101 | arguments. See ``create-vault-ca --help`` for details. 102 | 103 | NOTE: set ``--vault-token`` option using ``Initial Root Token`` from 104 | above. 105 | 106 | .. code:: bash 107 | 108 | ❯❯❯ ~ create-vault-ca --domain=test.org --component=test --vault-addr="http://127.0.0.1:8200" --vault-token=087efd94-3680-0ff4-25b7-a92177cd3c46 109 | Are you sure this script have not been already run on this vault? It can break / override configs [y|N] y 110 | Successfully mounted 'pki' at 'pki/test.org'! 111 | Successfully tuned mount 'pki/test.org'! 112 | Key Value 113 | --- ----- 114 | certificate -----BEGIN CERTIFICATE----- 115 | MIIC9jCCAd6gAwIBAgIUKybrEs7kUvRSgepQuImxonoznCwwDQYJKoZIhvcNAQEL 116 | BQAwEzERMA8GA1UEAxMIdGVzdC5vcmcwHhcNMTcwNTE0MTcyNDMwWhcNMjIwNTEz 117 | MTcyNTAwWjATMREwDwYDVQQDEwh0ZXN0Lm9yZzCCASIwDQYJKoZIhvcNAQEBBQAD 118 | ggEPADCCAQoCggEBALeVV8zUKwhYJz0eVg+6rWfCPz+GdxxIXeiChULAU+zHWvDf 119 | Jxye9JrcTdc/XUI0ZSw33F2JEjLkDasdchfL4ESRbUTdnJj1kYW6KEF9X3rhL/AM 120 | hdX+EqUQ9yvXRlvcSyGObVD7ayRUcG2IDpCLRuFW5bkw+MxvSjyzIf6+W3bs5DVz 121 | mFKqRv5Y3ycsuzc8CiDjxj/1LZWvBfqUFf8jePO0bzL3kw7uViZA4fJ23wPLqTyq 122 | IRX52ODZFC3SeyF600lerCLGY4Bgol8YtZwjsx+MxpPnszlkitxT2wjAghfPTV0W 123 | 8BebQi4D+CN4A4C6joyGZrdagzsUF3LoeGoDFh8CAwEAAaNCMEAwDgYDVR0PAQH/ 124 | BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHovOm1ZHkAsmCGKn+u3 125 | QmlCrriZMA0GCSqGSIb3DQEBCwUAA4IBAQBgDE//Tktbe16VSSrqP8MNYGtMG+jZ 126 | PV2Ao7FCrgSPwjBQHPXR1fh+g4MMG4S9iI8QtXIz49/ZYXfXPU6LPq8W/zrIlf/g 127 | 7PODdOo/w7LA7CBHG6ceQtRXHuaMJvJ8EybTQ4vc7LK2FMdEZbBQQkQfnCunR8bz 128 | oACVTooX2DkSPHCM24XSBsmMsHxImEYrjzsr0RyU+R9Tq+rdhjoEyUzQxklIecTq 129 | 8D1yfIrgIfYfT1qf6n2bEb+xIfk47v8yXlIUS3KLDadUtqybHIzsbSKEwiQse7rF 130 | AOoUPGoZMSJAr52y0SW2QE8mJoGyX0HeqeX2ocrKw3WvwXF1oHpOB6Au 131 | -----END CERTIFICATE----- 132 | expiration 1652462700 133 | issuing_ca -----BEGIN CERTIFICATE----- 134 | MIIC9jCCAd6gAwIBAgIUKybrEs7kUvRSgepQuImxonoznCwwDQYJKoZIhvcNAQEL 135 | BQAwEzERMA8GA1UEAxMIdGVzdC5vcmcwHhcNMTcwNTE0MTcyNDMwWhcNMjIwNTEz 136 | MTcyNTAwWjATMREwDwYDVQQDEwh0ZXN0Lm9yZzCCASIwDQYJKoZIhvcNAQEBBQAD 137 | ggEPADCCAQoCggEBALeVV8zUKwhYJz0eVg+6rWfCPz+GdxxIXeiChULAU+zHWvDf 138 | Jxye9JrcTdc/XUI0ZSw33F2JEjLkDasdchfL4ESRbUTdnJj1kYW6KEF9X3rhL/AM 139 | hdX+EqUQ9yvXRlvcSyGObVD7ayRUcG2IDpCLRuFW5bkw+MxvSjyzIf6+W3bs5DVz 140 | mFKqRv5Y3ycsuzc8CiDjxj/1LZWvBfqUFf8jePO0bzL3kw7uViZA4fJ23wPLqTyq 141 | IRX52ODZFC3SeyF600lerCLGY4Bgol8YtZwjsx+MxpPnszlkitxT2wjAghfPTV0W 142 | 8BebQi4D+CN4A4C6joyGZrdagzsUF3LoeGoDFh8CAwEAAaNCMEAwDgYDVR0PAQH/ 143 | BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHovOm1ZHkAsmCGKn+u3 144 | QmlCrriZMA0GCSqGSIb3DQEBCwUAA4IBAQBgDE//Tktbe16VSSrqP8MNYGtMG+jZ 145 | PV2Ao7FCrgSPwjBQHPXR1fh+g4MMG4S9iI8QtXIz49/ZYXfXPU6LPq8W/zrIlf/g 146 | 7PODdOo/w7LA7CBHG6ceQtRXHuaMJvJ8EybTQ4vc7LK2FMdEZbBQQkQfnCunR8bz 147 | oACVTooX2DkSPHCM24XSBsmMsHxImEYrjzsr0RyU+R9Tq+rdhjoEyUzQxklIecTq 148 | 8D1yfIrgIfYfT1qf6n2bEb+xIfk47v8yXlIUS3KLDadUtqybHIzsbSKEwiQse7rF 149 | AOoUPGoZMSJAr52y0SW2QE8mJoGyX0HeqeX2ocrKw3WvwXF1oHpOB6Au 150 | -----END CERTIFICATE----- 151 | serial_number 2b:26:eb:12:ce:e4:52:f4:52:81:ea:50:b8:89:b1:a2:7a:33:9c:2c 152 | 153 | Success! Data written to: pki/test.org/roles/cert 154 | Policy 'pki/test.org/cert' written. 155 | Success! Data written to: auth/token/roles/services 156 | Success! Data written to: auth/token/roles/users 157 | 158 | Generating services token (REMEMBER TO SAVE IT) 159 | Key Value 160 | --- ----- 161 | token 9a6b0ee1-c159-3710-dc3f-7641a5ef9222 162 | token_accessor 3730bbec-d8ae-eac0-cc26-c4fb6efa3e0a 163 | token_duration 8760h0m0s 164 | token_renewable true 165 | token_policies [default pki/test.org/cert] 166 | 167 | Have you saved the services token above? [y|N] y 168 | 169 | Generating users token (REMEMBER TO SAVE IT) 170 | Key Value 171 | --- ----- 172 | token 3f2ebc35-1793-dc9e-f8da-f6dd6d081ca2 173 | token_accessor 7fcf4113-4918-54a1-d24c-8533b3b10e53 174 | token_duration 8760h0m0s 175 | token_renewable true 176 | token_policies [default pki/test.org/cert] 177 | 178 | Have you saved the users token above? [y|N] y 179 | 180 | To boostrap the CA use "fetch-ssl-cert -c test -n -t -b -o " 181 | To create / renew a certificate use "fetch-ssl-cert -c test -n -t -o " 182 | 183 | From now on, you can use one of the two tokens created during the CA 184 | setup: 185 | 186 | - services: used by automated services to fetch certificate/key pairs. 187 | - users: used by humans to fetch certificate/key pairs. 188 | 189 | Secure Vault with TLS 190 | ~~~~~~~~~~~~~~~~~~~~~ 191 | 192 | Once the CA is setup, Vault itself need to get its own certificate/key 193 | pair and the CA need to be downloaded and bootstrapped into the system. 194 | 195 | I am assuming you are on Debian and you have ``update-ca-certificates`` 196 | available. 197 | 198 | NOTE: from now on the token used is ``services`` from above. 199 | 200 | .. code:: bash 201 | 202 | ❯❯❯ fetch-ssl-cert -c test -n vault.test.org -d test.org -i 127.0.0.1 -t 9a6b0ee1-c159-3710-dc3f-7641a5ef9222 -b -A http://127.0.0.1:8200 -D 203 | 2017-05-14 18:52:58,443 __init__.py:44 DEBUG:vault address is `http://127.0.0.1:8200` 204 | 2017-05-14 18:52:58,443 __init__.py:174 DEBUG:request url is `http://127.0.0.1:8200/v1/pki/test.org/issue/cert` 205 | 2017-05-14 18:52:58,443 __init__.py:131 DEBUG:requesting new cert / key part for CA domain: `test.org`, component: `test`, common_name: `vault.test.org`, ip_sans: `127.0.0.1`, alt_names: `None`, ttl: `8760h` 206 | 2017-05-14 18:52:58,450 connectionpool.py:207 DEBUG:Starting new HTTP connection (1): 127.0.0.1 207 | 2017-05-14 18:52:58,590 connectionpool.py:395 DEBUG:http://127.0.0.1:8200 "PUT /v1/pki/test.org/issue/cert HTTP/1.1" 200 None 208 | 2017-05-14 18:52:58,591 __init__.py:59 DEBUG:directory `/usr/local/share/ca-certificates/test.org` already exists, skipping creation 209 | 2017-05-14 18:52:58,591 __init__.py:106 DEBUG:writing certificate for vault.test.org on /usr/local/share/ca-certificates/test.org/test-vault.test.org.pem 210 | 2017-05-14 18:52:58,591 __init__.py:109 DEBUG:writing private key for vault.test.org on /usr/local/share/ca-certificates/test.org/test-vault.test.org.key 211 | 2017-05-14 18:52:58,591 __init__.py:114 DEBUG:writing CA on /usr/local/share/ca-certificates/test.org/test.crt 212 | 213 | Now that the certificate/key pair and the CA are saved on the disk, we 214 | need to update the system certificate authorities 215 | 216 | .. code:: bash 217 | 218 | ❯❯❯ update-ca-certificates --fresh 219 | Updating certificates in /etc/ssl/certs... 1 added, 0 removed; done. 220 | Running hooks in /etc/ca-certificates/update.d....done. 221 | 222 | Stop vault and restart it using the other configuration from ``example`` 223 | directory and repeat the unseal process. 224 | 225 | .. code:: bash 226 | 227 | ❯❯❯ vault server -config example/vault.hcl.ssl 228 | 229 | Now vault is fully secure and usable. 230 | 231 | NOTE: remember to register a local DNS for ``vault.test.org`` or use the 232 | command line option to specify the Vault address. 233 | 234 | Fetch certificate/key pair 235 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 236 | 237 | Let's fetch a certificate/key pair for a test domain. 238 | 239 | .. code:: bash 240 | 241 | fetch-ssl-cert -c test -n test.test.org -d test.org -t 9a6b0ee1-c159-3710-dc3f-7641a5ef9222 -A https://127.0.0.1:8200 -D 242 | 2017-05-14 18:52:58,443 __init__.py:44 DEBUG:vault address is `https://127.0.0.1:8200` 243 | 2017-05-14 18:52:58,443 __init__.py:174 DEBUG:request url is `https://127.0.0.1:8200/v1/pki/test.org/issue/cert` 244 | 2017-05-14 18:52:58,443 __init__.py:131 DEBUG:requesting new cert / key part for CA domain: `test.org`, component: `test`, common_name: `test.test.org`, ip_sans: `None`, alt_names: `None`, ttl: `8760h` 245 | 2017-05-14 18:52:58,450 connectionpool.py:207 DEBUG:Starting new HTTPS connection (1): 127.0.0.1 246 | 2017-05-14 18:52:58,590 connectionpool.py:395 DEBUG:https://127.0.0.1:8200 "PUT /v1/pki/test.org/issue/cert HTTP/1.1" 200 None 247 | 2017-05-14 18:52:58,591 __init__.py:59 DEBUG:directory `/usr/local/share/ca-certificates/test.org` already exists, skipping creation 248 | 2017-05-14 18:52:58,591 __init__.py:106 DEBUG:writing certificate for test.test.org on /usr/local/share/ca-certificates/test.org/test-test.test.org.pem 249 | 2017-05-14 18:52:58,591 __init__.py:109 DEBUG:writing private key for vault.test.org on /usr/local/share/ca-certificates/test.org/test-test.test.org.key 250 | 251 | .. |Build Status| image:: https://travis-ci.org/crisidev/vault-ca.svg?branch=master 252 | :target: https://travis-ci.org/crisidev/vault-ca 253 | .. |codecov| image:: https://codecov.io/gh/crisidev/vault-ca/branch/master/graph/badge.svg 254 | :target: https://codecov.io/gh/crisidev/vault-ca 255 | .. |Code Climate| image:: https://codeclimate.com/github/crisidev/vault-ca/badges/gpa.svg 256 | :target: https://codeclimate.com/github/crisidev/vault-ca 257 | .. |Issue Count| image:: https://codeclimate.com/github/crisidev/vault-ca/badges/issue_count.svg 258 | :target: https://codeclimate.com/github/crisidev/vault-ca 259 | -------------------------------------------------------------------------------- /example/vault.hcl.init: -------------------------------------------------------------------------------- 1 | cluster_name = "test-cluster" 2 | 3 | backend "file" { 4 | path = "/opt/lib/vault" 5 | } 6 | 7 | listener "tcp" { 8 | address = "127.0.0.1:8200" 9 | tls_disable = 1 10 | } 11 | 12 | # 1 year default ttl 13 | default_lease_ttl = "8760h" 14 | # 5 years max ttl 15 | max_lease_ttl = "43800h" 16 | -------------------------------------------------------------------------------- /example/vault.hcl.ssl: -------------------------------------------------------------------------------- 1 | cluster_name = "test-cluster" 2 | 3 | backend "file" { 4 | path = "/opt/lib/vault" 5 | } 6 | 7 | listener "tcp" { 8 | address = "127.0.0.1:8200" 9 | tls_cert_file = "/usr/local/share/ca-certificates/test.org/test-vault.test.org.pem" 10 | tls_key_file = "/usr/local/share/ca-certificates/test.org/test-vault.test.org.key" 11 | } 12 | 13 | # 1 year default ttl 14 | default_lease_ttl = "8760h" 15 | # 5 years max ttl 16 | max_lease_ttl = "43800h" 17 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | 4 | [yapf] 5 | based_on_style = google 6 | column_limit=119 7 | allow_multiline_lambdas=true 8 | blank_line_before_nested_class_or_def=true 9 | coalesce_brackets=true 10 | continuation_indent_width=4 11 | dedent_closing_brackets=true 12 | indent_width=4 13 | spaces_before_comment=2 14 | space_between_ending_comma_and_closing_bracket=true 15 | split_arguments_when_comma_terminated=true 16 | split_before_first_argument=true 17 | split_before_logical_operator=true 18 | split_before_named_assigns=true 19 | 20 | [aliases] 21 | test = pytest 22 | 23 | [tool:pytest] 24 | addopts = -v --cov-report term-missing --cov=vault_ca tests/ 25 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from distutils.core import setup 3 | from setuptools import find_packages, Command 4 | 5 | VERSION = 0.6 6 | 7 | 8 | class FormatCommand(Command): 9 | description = "Python auto-formatter" 10 | user_options = [] 11 | 12 | def initialize_options(self): 13 | pass 14 | 15 | def finalize_options(self): 16 | pass 17 | 18 | def run(self): 19 | import yapf 20 | yapf.main([sys.executable, '--in-place', '--recursive', 'bin', 'vault_ca', 'tests']) 21 | 22 | 23 | cmdclass = { 24 | 'format': FormatCommand 25 | } 26 | 27 | setup( 28 | name='vault-ca', 29 | version='{}'.format(VERSION), 30 | description='Set of utils to create your own CA using hashicorp Vault', 31 | author='Matteo Bigoi', 32 | author_email='bigo@crisidev.org', 33 | url='https://github.com/crisidev/vault-ca', 34 | license='GPLv3', 35 | download_url='https://github.com/crisidev/vault-ca/archive/{}.tar.gz'.format(VERSION), 36 | keywords=['ssl', 'certificate-authority', 'vault'], 37 | classifiers=[ 38 | 'Development Status :: 3 - Alpha', 39 | 'Intended Audience :: Developers', 40 | 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 41 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 42 | 'Programming Language :: Unix Shell', 43 | 'Programming Language :: Python :: 2', 44 | 'Programming Language :: Python :: 2.7', 45 | 'Programming Language :: Python :: 3', 46 | 'Programming Language :: Python :: 3.4', 47 | 'Programming Language :: Python :: 3.4', 48 | 'Programming Language :: Python :: 3.5', 49 | 'Programming Language :: Python :: 3.6', 50 | ], 51 | packages=find_packages(exclude=['docs', 'tests']), 52 | scripts=['bin/fetch-ssl-cert', 'bin/create-vault-ca'], 53 | install_requires=['appdirs', 'pyparsing', 'pyopenssl', 'requests'], 54 | cmdclass=cmdclass, 55 | setup_requires=['pytest-runner'], 56 | tests_require=['pytest', 'pytest-cov', 'requests-mock'] 57 | ) 58 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crisidev/vault-ca/340d2012b3ac3373e5d3f911332f930eeaba685e/tests/__init__.py -------------------------------------------------------------------------------- /tests/fixtures/acomponent-test.test.org.key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEowIBAAKCAQEA8F+79CuWSEUmHPjeNN3y78qXZa2Bo+7XQ72Us/lg6pYuh5ID 3 | qdawuv9ZijR6diOc5cJIT74RlW+RwuAELvhvVkuuXLo4YDffZa0QEsQvRpq/8ezc 4 | oX1sUL6hiCPRlL5GEEdbDhiuVzx3OdWc79yGJouzFeMh0bXBpdEQGKxUgiPvNHB9 5 | ZR0oC1mrksxx4KfYIlmbsNGpRyTe4JI0ezlLAYhpXRqAB6lGRPCbif+0H1RVPV1h 6 | W0yj/dyXLIRsgZro1MfQLRsFmhY95yFLXZRTVtTbZZsIqPCYEVJHYSbk+8r2BRYO 7 | VzU+DeaRhTqo7wjPR3uUWO/0J4Ql5DnUGQ8raQIDAQABAoIBAEFjiZmukb8vMGMJ 8 | QElZZ1Db57t9K5sQyfZfiCg9WqP2Hso6aky1XnZAKHd0NywUHAZUh59JsTbZlulQ 9 | T1MHuiHbjJ8k+VkTWe4q2giA3etzBWwmZw53NBPzB7YlKEoySJT9FEQNar/IbxaI 10 | iZymfMfXkOwPUY/excL50Esl9gdAgEbMWLdLhEyT9P1zrleG1mfF0QngHLUmm8Y9 11 | f+TOneVAGSElE0oNeUgb6hCzBTzpwwd9LIlPFMm0gUIipq4maRz4Q8O74pUANRHe 12 | OsK04LkZxqfp+s64UGBGqAq1d0TyNngOk/F6iehJEpL9XGetabzX1KMst+xdfHDu 13 | Wd6bVAECgYEA9tnKHE+hRLm7Z3daIIJKkf1WvViPLXnWGi9qf2LL5RgMpzrs7T18 14 | 2W1aM/dQwP2/6N5O6X+Jy8/IXwPXApYb0LorKAlt+GDf5VxcO82WsqOZzvBq2QyG 15 | /QZoDgDCzfGURSzFh+QCFbXPCGHI/oN/ZZkLbHs9ZceoGTOP0Av9T8kCgYEA+Uh9 16 | mvx+xAOOgW40ZyYdqaWNvcgwd+9+Mthsmh++Sf/MTy7IXKNzFUjHtl5mQ19lq3o4 17 | vfRK4mSC6rHlv5sCsdD0/EkhYyM7JBJVOHHXUzAt5h9d+3KNkxuV9VnDlJ8g33Or 18 | KXUd+M1zrqT3j8+9UPNl984OEUJuY6xuWvDLDqECgYEA43fHlZUPT4wzE+HYjFJj 19 | sumXT33W2hoGYDTHV0FMD/y8VDGpd+gMLzNkRrSklmJ9wHFymBoteUEsK9oW/Ewk 20 | r4+OCyO9UX67cthMKdOGBXFaX2YNn5q6nViU9CphWHM/pQrfrxw9i5HwiJHLLDUy 21 | ZQXFkB50cmCsFyT7ZcRWlXkCgYBYkLyvd83B7lGPAoxzqUMYpsz5BErUEa6Qefv7 22 | thNxTwRTjZd58khM45Kw5FEI1rfUeJP4SPbiADvTDmlF7djDPC4OBB1sj3PPmQPW 23 | DfwmfhOQksxdLZHHFiHtDXtDLlYLjZjeHdIMN1JGVi3uViw4uoEbzYWJ9EQr/XMn 24 | tC0wgQKBgH3dDgZhAHWgGJ9lUaEIy/wNN8RmESe2KuO1c7WcNZk7XfrjKw3VVmcF 25 | kNiTnBbdydQrTdDg9rHOQ+1UaVdZVxv5grnPtUHuKGFluCJQiY8yVebq3pQzBvE/ 26 | 1GDU1z0AVajolU0UOjCtflCUQYU//SuicOi35lPHeKmMoyNajKb7 27 | -----END RSA PRIVATE KEY----- -------------------------------------------------------------------------------- /tests/fixtures/acomponent-test.test.org.pem.empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/crisidev/vault-ca/340d2012b3ac3373e5d3f911332f930eeaba685e/tests/fixtures/acomponent-test.test.org.pem.empty -------------------------------------------------------------------------------- /tests/fixtures/acomponent-test.test.org.pem.ko: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDcjCCAlqgAwIBAgIUANUjICodQ7oIwxjcioaSpIZ1/1gwDQYJKoZIhvcNAQEL 3 | BQAwFTETMBEGA1UEAxMKY2FyZGluYS5saTAeFw0xNzA1MTMxNTE4NTJaFw0xODA1 4 | MTMxNTE5MjJaMEIxEzARBgNVBAoTCmNhcmRpbmEubGkxEzARBgNVBAsTCmNhdHRl 5 | ZHJhbGUxFjAUBgNVBAMTDXRlc3QudGVzdC5vcmcwggEiMA0GCSqGSIb3DQEBAQUA 6 | A4IBDwAwggEKAoIBAQDFVmdLboH84egU4FDU4ixJ92x6vhC3bN5b995voItj2vMU 7 | qeWWu7RuuwZgmK3n+4KjkdGKqvISPuSLSL7txs8oOBuS5Jp8QZUGlcra9s3URBHa 8 | KR2wD1pmqyDS8q635aptxoQmbpDVDJmrYSIYJx9GKcCFJOQUU6Gy3IPogTptJLoA 9 | SMv+V1W+0MZ3U1eBGfrQBPRL5GqshMXKW1DCabwqZ2tSfZjBZB/3xZnIJDEOBKqQ 10 | 0KRtem3eP6QGxAABT9Oz4hN/T+dThNoeANIdYX+K3jrJFH1wHc920SyAf/c1gwm+ 11 | FgQUlaOEHg9e/Htx261ihndVKUdQNNQwHwYDVR0jBBgwFoAUtxhSao9IFhgcFUEW 12 | hy7TxhdysF0wGAYDVR0RBBEwD4INdGVzdC50ZXN0Lm9yZzANBgkqhkiG9w0BAQsF 13 | AAOCAQEACpqeO6ci6GH/pWRWrKVyPx+x07CiLw1AqLhRfZtQ1ZUyRg8uEwHKWJcs 14 | HecQourJpcrx1ABFiRvw2mgipoL6R2DlaWhZ941aojs4F/LyWAUDCJ2+qaZj5PNl 15 | gmaPLfg5rmd4BQQTpXI00oOkPf8PAA5kQZv5f6wNwRQolaGBAzZoroBHN7yS3XST 16 | uvqvNZNJYFpKQDspOMVCgcxjXE6AHPdsSRM2yMwTXdvf65bdcAut0/VoE1BB/YMh 17 | MEgJkL1TugvCNn5aJoOPTVtLauFo6xSnZGqP6BHEAVTs2sZpwFl3l4ZlflychdH7 18 | IFvdCcWmZkk/nk3O893MF3T8hchbzw== 19 | -------------------------------------------------------------------------------- /tests/fixtures/acomponent-test.test.org.pem.ok: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDcjCCAlqgAwIBAgIUANUjICodQ7oIwxjcioaSpIZ1/1gwDQYJKoZIhvcNAQEL 3 | BQAwFTETMBEGA1UEAxMKY2FyZGluYS5saTAeFw0xNzA1MTMxNTE4NTJaFw0xODA1 4 | MTMxNTE5MjJaMEIxEzARBgNVBAoTCmNhcmRpbmEubGkxEzARBgNVBAsTCmNhdHRl 5 | ZHJhbGUxFjAUBgNVBAMTDXRlc3QudGVzdC5vcmcwggEiMA0GCSqGSIb3DQEBAQUA 6 | A4IBDwAwggEKAoIBAQDFVmdLboH84egU4FDU4ixJ92x6vhC3bN5b995voItj2vMU 7 | qeWWu7RuuwZgmK3n+4KjkdGKqvISPuSLSL7txs8oOBuS5Jp8QZUGlcra9s3URBHa 8 | KR2wD1pmqyDS8q635aptxoQmbpDVDJmrYSIYJx9GKcCFJOQUU6Gy3IPogTptJLoA 9 | SMv+V1W+0MZ3U1eBGfrQBPRL5GqshMXKW1DCabwqZ2tSfZjBZB/3xZnIJDEOBKqQ 10 | 0KRtem3eP6QGxAABT9Oz4hN/T+dThNoeANIdYX+K3jrJFH1wHc920SyAf/c1gwm+ 11 | Tl/qWxyB5bw9x9/m5xyEOm10qnW6cwPjXzMgQR2LAgMBAAGjgYwwgYkwDgYDVR0P 12 | AQH/BAQDAgOoMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAdBgNVHQ4E 13 | FgQUlaOEHg9e/Htx261ihndVKUdQNNQwHwYDVR0jBBgwFoAUtxhSao9IFhgcFUEW 14 | hy7TxhdysF0wGAYDVR0RBBEwD4INdGVzdC50ZXN0Lm9yZzANBgkqhkiG9w0BAQsF 15 | AAOCAQEACpqeO6ci6GH/pWRWrKVyPx+x07CiLw1AqLhRfZtQ1ZUyRg8uEwHKWJcs 16 | HecQourJpcrx1ABFiRvw2mgipoL6R2DlaWhZ941aojs4F/LyWAUDCJ2+qaZj5PNl 17 | gmaPLfg5rmd4BQQTpXI00oOkPf8PAA5kQZv5f6wNwRQolaGBAzZoroBHN7yS3XST 18 | uvqvNZNJYFpKQDspOMVCgcxjXE6AHPdsSRM2yMwTXdvf65bdcAut0/VoE1BB/YMh 19 | MEgJkL1TugvCNn5aJoOPTVtLauFo6xSnZGqP6BHEAVTs2sZpwFl3l4ZlflychdH7 20 | IFvdCcWmZkk/nk3O893MF3T8hchbzw== 21 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /tests/fixtures/acomponent.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIC9jCCAd6gAwIBAgIUKybrEs7kUvRSgepQuImxonoznCwwDQYJKoZIhvcNAQEL 3 | BQAwEzERMA8GA1UEAxMIdGVzdC5vcmcwHhcNMTcwNTE0MTcyNDMwWhcNMjIwNTEz 4 | MTcyNTAwWjATMREwDwYDVQQDEwh0ZXN0Lm9yZzCCASIwDQYJKoZIhvcNAQEBBQAD 5 | ggEPADCCAQoCggEBALeVV8zUKwhYJz0eVg+6rWfCPz+GdxxIXeiChULAU+zHWvDf 6 | Jxye9JrcTdc/XUI0ZSw33F2JEjLkDasdchfL4ESRbUTdnJj1kYW6KEF9X3rhL/AM 7 | hdX+EqUQ9yvXRlvcSyGObVD7ayRUcG2IDpCLRuFW5bkw+MxvSjyzIf6+W3bs5DVz 8 | mFKqRv5Y3ycsuzc8CiDjxj/1LZWvBfqUFf8jePO0bzL3kw7uViZA4fJ23wPLqTyq 9 | IRX52ODZFC3SeyF600lerCLGY4Bgol8YtZwjsx+MxpPnszlkitxT2wjAghfPTV0W 10 | 8BebQi4D+CN4A4C6joyGZrdagzsUF3LoeGoDFh8CAwEAAaNCMEAwDgYDVR0PAQH/ 11 | BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHovOm1ZHkAsmCGKn+u3 12 | QmlCrriZMA0GCSqGSIb3DQEBCwUAA4IBAQBgDE//Tktbe16VSSrqP8MNYGtMG+jZ 13 | PV2Ao7FCrgSPwjBQHPXR1fh+g4MMG4S9iI8QtXIz49/ZYXfXPU6LPq8W/zrIlf/g 14 | 7PODdOo/w7LA7CBHG6ceQtRXHuaMJvJ8EybTQ4vc7LK2FMdEZbBQQkQfnCunR8bz 15 | oACVTooX2DkSPHCM24XSBsmMsHxImEYrjzsr0RyU+R9Tq+rdhjoEyUzQxklIecTq 16 | 8D1yfIrgIfYfT1qf6n2bEb+xIfk47v8yXlIUS3KLDadUtqybHIzsbSKEwiQse7rF 17 | AOoUPGoZMSJAr52y0SW2QE8mJoGyX0HeqeX2ocrKw3WvwXF1oHpOB6Au 18 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /tests/test_vault_ca.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import datetime 4 | 5 | import pytest 6 | import OpenSSL 7 | import requests 8 | import requests_mock 9 | 10 | import vault_ca 11 | from vault_ca import VaultCA, VaultCAError 12 | 13 | 14 | @pytest.fixture 15 | def vault_ca_obj(tmpdir): 16 | temp_dir = str(tmpdir) 17 | kwargs = { 18 | 'component': 'acomponent', 19 | 'domain': 'test.org', 20 | 'vault_token': 'atoken', 21 | 'bootstrap_ca': False, 22 | 'ssl_verify': True, 23 | 'output_dir': temp_dir, 24 | 'ca_path': temp_dir 25 | } 26 | return VaultCA(kwargs) 27 | 28 | 29 | @pytest.fixture 30 | def vault_ca_obj_bootstap_ca(tmpdir): 31 | temp_dir = str(tmpdir) 32 | kwargs = { 33 | 'component': 'acomponent', 34 | 'domain': 'test.org', 35 | 'vault_token': 'atoken', 36 | 'bootstrap_ca': True, 37 | 'output_dir': temp_dir, 38 | 'ca_path': temp_dir 39 | } 40 | return VaultCA(kwargs) 41 | 42 | 43 | def test_validate_args_ok(): 44 | kwargs = { 45 | 'component': 'acomponent', 46 | 'domain': 'test.org', 47 | 'vault_token': 'atoken', 48 | } 49 | ca = VaultCA(kwargs) 50 | assert ca.component == 'acomponent' 51 | assert ca.domain == 'test.org' 52 | assert ca.vault_token == 'atoken' 53 | 54 | 55 | def test_validate_args_ko(): 56 | kwargs = { 57 | 'component': 'acomponent', 58 | 'vault_token': 'atoken', 59 | } 60 | with pytest.raises(VaultCAError): 61 | VaultCA(kwargs) 62 | 63 | kwargs = { 64 | 'domain': 'test.org', 65 | 'vault_token': 'atoken', 66 | } 67 | with pytest.raises(VaultCAError): 68 | VaultCA(kwargs) 69 | 70 | 71 | def test_manager_args(tmpdir): 72 | kwargs = { 73 | 'component': 'acomponent', 74 | 'domain': 'test.org', 75 | 'vault_token': 'atoken', 76 | 'bootstrap_ca': False, 77 | 'ssl_verify': True, 78 | 'output_dir': str(tmpdir), 79 | 'valid_interval': 2 80 | } 81 | ca = VaultCA(kwargs) 82 | assert ca.component == 'acomponent' 83 | assert ca.domain == 'test.org' 84 | assert ca.vault_token == 'atoken' 85 | assert not ca.bootstrap_ca 86 | assert ca.ssl_verify 87 | assert os.path.isdir(ca.output_dir) 88 | assert ca.vault_address == 'https://vault.test.org:8200' 89 | assert ca.valid_interval == 2 90 | 91 | 92 | def test_manager_args_bootstrap_ca(tmpdir): 93 | kwargs = { 94 | 'component': 'acomponent', 95 | 'domain': 'test.org', 96 | 'vault_token': 'atoken', 97 | 'bootstrap_ca': True, 98 | 'output_dir': str(tmpdir), 99 | } 100 | ca = VaultCA(kwargs) 101 | assert ca.component == 'acomponent' 102 | assert ca.domain == 'test.org' 103 | assert ca.vault_token == 'atoken' 104 | assert ca.bootstrap_ca 105 | assert not ca.ssl_verify 106 | assert os.path.isdir(ca.output_dir) 107 | assert ca.vault_address == 'https://vault.test.org:8200' 108 | assert ca.valid_interval == 1 109 | 110 | 111 | def test_make_dirs(vault_ca_obj, tmpdir): 112 | temp_dir = str(tmpdir) 113 | vault_ca_obj._make_dirs(os.path.join(temp_dir, 'atest')) 114 | assert os.path.isdir(os.path.join(temp_dir, 'atest')) 115 | # test it second time to increase the coverage 116 | vault_ca_obj._make_dirs(os.path.join(temp_dir, 'atest')) 117 | assert os.path.isdir(os.path.join(temp_dir, 'atest')) 118 | 119 | 120 | def test_parse_asn1_generalizedtime_ok(vault_ca_obj): 121 | timestamp = '20220510141643Z' 122 | parsed_timestamp = vault_ca_obj._parse_asn1_generalizedtime(timestamp) 123 | assert parsed_timestamp.year == 2022 124 | assert parsed_timestamp.month == 5 125 | assert parsed_timestamp.day == 10 126 | assert parsed_timestamp.hour == 14 127 | assert parsed_timestamp.minute == 16 128 | assert parsed_timestamp.second == 43 129 | 130 | 131 | def test_parse_asn1_generalizedtime_ko(vault_ca_obj): 132 | timestamp = '20220510141643' 133 | with pytest.raises(VaultCAError): 134 | vault_ca_obj._parse_asn1_generalizedtime(timestamp) 135 | timestamp = 'astring' 136 | with pytest.raises(VaultCAError): 137 | vault_ca_obj._parse_asn1_generalizedtime(timestamp) 138 | timestamp = '' 139 | with pytest.raises(VaultCAError): 140 | vault_ca_obj._parse_asn1_generalizedtime(timestamp) 141 | 142 | 143 | def test_load_certificate_ok(vault_ca_obj): 144 | pem = vault_ca_obj._load_certificate('tests/fixtures/acomponent-test.test.org.pem.ok') 145 | assert pem.get_signature_algorithm() == b'sha256WithRSAEncryption' 146 | 147 | 148 | def test_load_certificate_ko(vault_ca_obj): 149 | with pytest.raises(VaultCAError): 150 | vault_ca_obj._load_certificate('tests/fixtures/acomponent-test.test.org.pem.ko') 151 | 152 | 153 | def test_load_certificate_empty(vault_ca_obj): 154 | with pytest.raises(VaultCAError): 155 | vault_ca_obj._load_certificate('tests/fixtures/acomponent-test.test.org.pem.empty') 156 | 157 | 158 | def test_is_certificate_valid_true(vault_ca_obj, monkeypatch): 159 | 160 | class MockX509(OpenSSL.crypto.X509): 161 | 162 | def get_notAfter(self): 163 | return b'20220510141643Z' 164 | 165 | monkeypatch.setattr(OpenSSL.crypto, 'X509', MockX509) 166 | assert vault_ca_obj._is_certificate_valid('tests/fixtures/acomponent-test.test.org.pem.ok') 167 | 168 | 169 | def test_is_certificate_valid_false(vault_ca_obj, monkeypatch): 170 | 171 | class MockX509(OpenSSL.crypto.X509): 172 | 173 | def get_notAfter(self): 174 | return b'20000510141643Z' 175 | 176 | monkeypatch.setattr(OpenSSL.crypto, 'X509', MockX509) 177 | 178 | assert not vault_ca_obj._is_certificate_valid('tests/fixtures/acomponent-test.test.org.pem.ok') 179 | 180 | 181 | def test_is_certificate_valid_not_exists(vault_ca_obj): 182 | assert not vault_ca_obj._is_certificate_valid('tests/fixtures/a-non-existent-cert.pem') 183 | 184 | 185 | def test_is_certificate_valid_false_less_than_24h(vault_ca_obj, monkeypatch): 186 | 187 | class MockX509(OpenSSL.crypto.X509): 188 | 189 | def get_notAfter(self): 190 | return b'20000510141643Z' 191 | 192 | class MockDatetime(datetime.datetime): 193 | 194 | @classmethod 195 | def now(cls): 196 | return datetime.datetime(2000, 5, 9, 15, 16, 43, 100000) 197 | 198 | monkeypatch.setattr(OpenSSL.crypto, 'X509', MockX509) 199 | monkeypatch.setattr(vault_ca, 'datetime', MockDatetime) 200 | 201 | assert not vault_ca_obj._is_certificate_valid('tests/fixtures/acomponent-test.test.org.pem.ok') 202 | 203 | 204 | def test_is_certificate_valid_true_more_than_24h(vault_ca_obj, monkeypatch): 205 | 206 | class MockX509(OpenSSL.crypto.X509): 207 | 208 | def get_notAfter(self): 209 | return b'20000510141643Z' 210 | 211 | class MockDatetime(datetime.datetime): 212 | 213 | @classmethod 214 | def now(cls): 215 | return datetime.datetime(2000, 5, 9, 13, 16, 43, 100000) 216 | 217 | monkeypatch.setattr(OpenSSL.crypto, 'X509', MockX509) 218 | monkeypatch.setattr(vault_ca, 'datetime', MockDatetime) 219 | 220 | assert vault_ca_obj._is_certificate_valid('tests/fixtures/acomponent-test.test.org.pem.ok') 221 | 222 | 223 | def test_write_files(vault_ca_obj): 224 | component = "acomponent" 225 | common_name = "test.test.org" 226 | cert_data = open('tests/fixtures/acomponent-test.test.org.pem.ok', 'r').read() 227 | priv_key_data = open('tests/fixtures/acomponent-test.test.org.key', 'r').read() 228 | ca_data = open('tests/fixtures/acomponent.crt', 'r').read() 229 | cert_file = os.path.join(vault_ca_obj.output_dir, "{}-{}.pem".format(component, common_name)) 230 | priv_key_file = os.path.join(vault_ca_obj.output_dir, "{}-{}.key".format(component, common_name)) 231 | ca_file = os.path.join(vault_ca_obj.output_dir, "{}.crt".format(component)) 232 | vault_ca_obj._write_files('test.test.org', cert_data, cert_file, priv_key_data, priv_key_file, ca_data, ca_file) 233 | with open(cert_file, 'r') as pem: 234 | assert pem.read() == cert_data 235 | with open(priv_key_file, 'r') as key: 236 | assert key.read() == priv_key_data 237 | 238 | 239 | def test_write_files_boostrap_ca(vault_ca_obj_bootstap_ca): 240 | component = "acomponent" 241 | common_name = "test.test.org" 242 | cert_data = open('tests/fixtures/acomponent-test.test.org.pem.ok', 'r').read() 243 | priv_key_data = open('tests/fixtures/acomponent-test.test.org.key', 'r').read() 244 | ca_data = open('tests/fixtures/acomponent.crt', 'r').read() 245 | cert_file = os.path.join(vault_ca_obj_bootstap_ca.output_dir, "{}-{}.pem".format(component, common_name)) 246 | priv_key_file = os.path.join(vault_ca_obj_bootstap_ca.output_dir, "{}-{}.key".format(component, common_name)) 247 | ca_file = os.path.join(vault_ca_obj_bootstap_ca.output_dir, "{}.crt".format(component)) 248 | vault_ca_obj_bootstap_ca.ca_path = vault_ca_obj_bootstap_ca.output_dir 249 | vault_ca_obj_bootstap_ca._write_files( 250 | 'test.test.org', cert_data, cert_file, priv_key_data, priv_key_file, ca_data, ca_file 251 | ) 252 | with open(cert_file, 'r') as pem: 253 | assert pem.read() == cert_data 254 | with open(priv_key_file, 'r') as key: 255 | assert key.read() == priv_key_data 256 | with open(ca_file, 'r') as ca: 257 | assert ca.read() == ca_data 258 | 259 | 260 | def test_write_files_boostrap_ca_invalid_cert(vault_ca_obj_bootstap_ca, monkeypatch): 261 | 262 | def mock_is_certificate_valid(certificate_path): 263 | return True 264 | 265 | monkeypatch.setattr(vault_ca_obj_bootstap_ca, '_is_certificate_valid', mock_is_certificate_valid) 266 | 267 | component = "acomponent" 268 | common_name = "test.test.org" 269 | cert_data = open('tests/fixtures/acomponent-test.test.org.pem.ok', 'r').read() 270 | priv_key_data = open('tests/fixtures/acomponent-test.test.org.key', 'r').read() 271 | ca_data = open('tests/fixtures/acomponent.crt', 'r').read() 272 | cert_file = os.path.join(vault_ca_obj_bootstap_ca.output_dir, "{}-{}.pem".format(component, common_name)) 273 | priv_key_file = os.path.join(vault_ca_obj_bootstap_ca.output_dir, "{}-{}.key".format(component, common_name)) 274 | ca_file = os.path.join(vault_ca_obj_bootstap_ca.output_dir, "{}.crt".format(component)) 275 | vault_ca_obj_bootstap_ca.ca_path = vault_ca_obj_bootstap_ca.output_dir 276 | vault_ca_obj_bootstap_ca._write_files( 277 | 'test.test.org', cert_data, cert_file, priv_key_data, priv_key_file, ca_data, ca_file 278 | ) 279 | assert not os.path.isfile(cert_file) 280 | assert not os.path.isfile(ca_file) 281 | 282 | 283 | def test_prepare_json_data(vault_ca_obj): 284 | expected = {'common_name': 'common_name', 'ttl': '8760h'} 285 | json_data = vault_ca_obj._prepare_json_data('common_name') 286 | assert json.loads(json_data) == expected 287 | 288 | 289 | def test_prepare_json_data_alt_names(vault_ca_obj): 290 | expected = {'common_name': 'common_name', 'ttl': '8760h', 'alt_names': 'altname1,altname2'} 291 | json_data = vault_ca_obj._prepare_json_data('common_name', alt_names="altname1,altname2") 292 | assert json.loads(json_data) == expected 293 | 294 | 295 | def test_prepare_json_data_ip_sans(vault_ca_obj): 296 | expected = {'common_name': 'common_name', 'ttl': '8760h', 'ip_sans': '10.0.0.1,127.0.0.1'} 297 | json_data = vault_ca_obj._prepare_json_data('common_name', ip_sans="10.0.0.1,127.0.0.1") 298 | assert json.loads(json_data) == expected 299 | 300 | 301 | def test_prepare_json_data_ttl(vault_ca_obj): 302 | expected = {'common_name': 'common_name', 'ttl': '24h'} 303 | json_data = vault_ca_obj._prepare_json_data('common_name', ttl="24h") 304 | assert json.loads(json_data) == expected 305 | 306 | 307 | def test_analise_response_ok(vault_ca_obj): 308 | expected = {'akey': 'avalue'} 309 | 310 | class MockRequest: 311 | 312 | @property 313 | def ok(self): 314 | return True 315 | 316 | def json(self): 317 | return expected 318 | 319 | response = vault_ca_obj._analise_response(MockRequest()) 320 | assert response == expected 321 | 322 | 323 | def test_analise_reponse_ko(vault_ca_obj): 324 | 325 | class MockRequest: 326 | 327 | @property 328 | def ok(self): 329 | return False 330 | 331 | @property 332 | def status_code(self): 333 | return 404 334 | 335 | with pytest.raises(VaultCAError): 336 | vault_ca_obj._analise_response(MockRequest()) 337 | 338 | 339 | def test_analise_response_json_error(vault_ca_obj): 340 | 341 | class MockRequest: 342 | 343 | @property 344 | def ok(self): 345 | return True 346 | 347 | def json(self): 348 | 349 | class MockJSONDoc: 350 | 351 | def count(self, a, b, c): 352 | return 1 353 | 354 | def rfind(self, a, b, c): 355 | return 1 356 | 357 | raise json.JSONDecodeError('anerror', MockJSONDoc(), 2) 358 | 359 | with pytest.raises(VaultCAError): 360 | vault_ca_obj._analise_response(MockRequest()) 361 | 362 | 363 | def test_analise_response_vault_error(vault_ca_obj): 364 | expected = {'akey': 'avalue', 'errors': ['error1', 'error2']} 365 | 366 | class MockRequest: 367 | 368 | @property 369 | def ok(self): 370 | return True 371 | 372 | def json(self): 373 | return expected 374 | 375 | with pytest.raises(VaultCAError): 376 | vault_ca_obj._analise_response(MockRequest()) 377 | 378 | 379 | def test_extract_certificates_ok(vault_ca_obj): 380 | response = {'data': {'certificate': 'cert data', 'private_key': 'key data', 'issuing_ca': 'ca data'}} 381 | 382 | cert_data, priv_key_data, ca_data = vault_ca_obj._extract_certificates(response) 383 | assert cert_data == "cert data" 384 | assert priv_key_data == "key data" 385 | assert ca_data == "ca data" 386 | 387 | 388 | def test_extract_certificates_no_cert(vault_ca_obj): 389 | response = {'data': {'private_key': 'key data', 'issuing_ca': 'ca data'}} 390 | 391 | with pytest.raises(VaultCAError): 392 | vault_ca_obj._extract_certificates(response) 393 | 394 | 395 | def test_extract_certificates_no_key(vault_ca_obj): 396 | response = {'data': {'certificate': 'cert data', 'issuing_ca': 'ca data'}} 397 | 398 | with pytest.raises(VaultCAError): 399 | vault_ca_obj._extract_certificates(response) 400 | 401 | 402 | def test_extract_certificates_no_ca(vault_ca_obj): 403 | response = {'data': {'certificate': 'cert data', 'private_key': 'key data'}} 404 | 405 | with pytest.raises(VaultCAError): 406 | vault_ca_obj._extract_certificates(response) 407 | 408 | 409 | def test_fetch_200(vault_ca_obj): 410 | component = "acomponent" 411 | common_name = "test.test.org" 412 | cert_file = os.path.join(vault_ca_obj.output_dir, "{}-{}.pem".format(component, common_name)) 413 | priv_key_file = os.path.join(vault_ca_obj.output_dir, "{}-{}.key".format(component, common_name)) 414 | with requests_mock.Mocker() as mock: 415 | response = {'data': {'certificate': 'cert data', 'private_key': 'key data', 'issuing_ca': 'ca data'}} 416 | mock.put('https://vault.test.org:8200/v1/pki/test.org/issue/cert', json=response, status_code=200) 417 | vault_ca_obj.fetch('test.test.org', ip_sans='10.0.0.1', alt_names='alttest.test.org', ttl='24h') 418 | assert os.path.isfile(cert_file) 419 | assert os.path.isfile(priv_key_file) 420 | 421 | 422 | def test_fetch_404(vault_ca_obj): 423 | with requests_mock.Mocker() as mock: 424 | mock.put('https://vault.test.org:8200/v1/pki/test.org/issue/cert', json={}, status_code=404) 425 | with pytest.raises(VaultCAError): 426 | vault_ca_obj.fetch('test.test.org') 427 | 428 | 429 | def test_fetch_500(vault_ca_obj): 430 | with requests_mock.Mocker() as mock: 431 | mock.put('https://vault.test.org:8200/v1/pki/test.org/issue/cert', json={}, status_code=500) 432 | with pytest.raises(VaultCAError): 433 | vault_ca_obj.fetch('test.test.org') 434 | 435 | 436 | def test_fetch_connect_timeout(vault_ca_obj): 437 | with requests_mock.Mocker() as mock: 438 | mock.put('https://vault.test.org:8200/v1/pki/test.org/issue/cert', exc=requests.exceptions.ConnectTimeout) 439 | with pytest.raises(VaultCAError): 440 | vault_ca_obj.fetch('test.test.org') 441 | 442 | 443 | def test_fetch_connect_error(vault_ca_obj): 444 | with requests_mock.Mocker() as mock: 445 | mock.put('https://vault.test.org:8200/v1/pki/test.org/issue/cert', exc=requests.exceptions.ConnectionError) 446 | with pytest.raises(VaultCAError): 447 | vault_ca_obj.fetch('test.test.org') 448 | 449 | 450 | def test_fetch_valid_cert(vault_ca_obj, monkeypatch): 451 | 452 | def mock_is_certificate_valid(certificate_path): 453 | return True 454 | 455 | monkeypatch.setattr(vault_ca_obj, '_is_certificate_valid', mock_is_certificate_valid) 456 | 457 | component = "acomponent" 458 | common_name = "test.test.org" 459 | cert_file = os.path.join(vault_ca_obj.output_dir, "{}-{}.pem".format(component, common_name)) 460 | ca_file = os.path.join(vault_ca_obj.output_dir, "{}.crt".format(component)) 461 | with requests_mock.Mocker() as mock: 462 | response = {'data': {'certificate': 'cert data', 'private_key': 'key data', 'issuing_ca': 'ca data'}} 463 | mock.put('https://vault.test.org:8200/v1/pki/test.org/issue/cert', json=response, status_code=200) 464 | vault_ca_obj.fetch('test.test.org', ip_sans='10.0.0.1', alt_names='alttest.test.org', ttl='24h') 465 | assert not os.path.isfile(cert_file) 466 | assert not os.path.isfile(ca_file) 467 | -------------------------------------------------------------------------------- /vault_ca/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import logging 4 | from datetime import datetime, timedelta 5 | 6 | import requests 7 | from OpenSSL.crypto import load_certificate, FILETYPE_PEM, Error 8 | 9 | VERSION = 0.6 10 | 11 | # fix incompatibility between python 3.4 and 3.5+ json implementation 12 | if not hasattr(json, 'JSONDecodeError'): # pragma: nocover 13 | json.JSONDecodeError = ValueError 14 | 15 | 16 | class VaultCAError(Exception): 17 | """ 18 | VaultCA custom exception 19 | """ 20 | pass 21 | 22 | 23 | class VaultCA(object): 24 | """ 25 | Object to handle fetching ot certificate/key pairs and CA. 26 | """ 27 | ASN1_GENERALIZEDTIME_FORMAT = "%Y%m%d%H%M%SZ" 28 | DEFAULT_CERTIFICATE_TTL = '8760h' # 1 year 29 | DEFAULT_VALID_INTERVAL_DAYS = 1 30 | VAULT_ADDRESS = "https://vault.{}:8200" 31 | VAULT_PATH = "v1/pki/{}/issue/cert" 32 | CA_PATH = "/usr/local/share/ca-certificates/{}" 33 | MANDATORY_ARGS = ('component', 'domain', 'vault_token') 34 | 35 | def __init__(self, kwargs): 36 | """ 37 | Initialize object and its attributes. 38 | 39 | :param kwargs: arguments dictionary 40 | :type kwargs: dict 41 | """ 42 | self._validate_args(kwargs) 43 | self._manage_args(kwargs) 44 | 45 | def _manage_args(self, kwargs): 46 | """ 47 | Setup object attributes for later usage. 48 | 49 | :param kwargs: arguments dictionary 50 | :type kwargs: dict 51 | """ 52 | 53 | self.component = kwargs['component'] 54 | self.domain = kwargs['domain'] 55 | self.vault_token = kwargs['vault_token'] 56 | self.output_dir = kwargs.get('output_dir') or self.CA_PATH.format(self.domain) 57 | self.bootstrap_ca = kwargs.get('bootstrap_ca') 58 | if self.bootstrap_ca: 59 | self.ssl_verify = False 60 | else: 61 | self.ssl_verify = kwargs.get('ssl_verify') 62 | self.valid_interval = kwargs.get('valid_interval') or self.DEFAULT_VALID_INTERVAL_DAYS 63 | self.vault_address = kwargs.get('vault_address') or self.VAULT_ADDRESS.format(self.domain) 64 | self.ca_path = kwargs.get('ca_path') or self.CA_PATH.format(self.domain) 65 | logging.debug('vault address is `%s`', self.vault_address) 66 | 67 | def _validate_args(self, kwargs): 68 | """ 69 | Validate that mandatory arguments are present. 70 | 71 | :param kwargs: arguments dictionary 72 | :type kwargs: dict 73 | 74 | :raises VaultCAError: if there are missing mandatory arguments 75 | """ 76 | 77 | missing_args = [] 78 | for arg in self.MANDATORY_ARGS: 79 | if arg not in kwargs.keys(): 80 | logging.error("missing mandatory init argument `%s`", arg) 81 | missing_args.append(arg) 82 | if missing_args: 83 | raise VaultCAError("missing mandatory init arguments `%s`", ', '.join(missing_args)) 84 | 85 | def _make_dirs(self, directory): 86 | """ 87 | Create directory if not present. 88 | 89 | :param directory: directory to create 90 | :type directory: str 91 | """ 92 | if not os.path.exists(directory): 93 | os.makedirs(directory) 94 | 95 | def _parse_asn1_generalizedtime(self, timestamp): 96 | """ 97 | Parse a timestamp coming from PyOpenSSL X509 object into datetime. 98 | 99 | :param timestamp: ASN.1 GENERALIZEDTIME timestamp 100 | :type timestamp: str 101 | 102 | :return: parsed timestamp 103 | :rtype: datetime.datetime 104 | 105 | :raises VaultCAError: if the format is not parsable 106 | """ 107 | try: 108 | return datetime.strptime(timestamp, self.ASN1_GENERALIZEDTIME_FORMAT) 109 | except ValueError as e: 110 | logging.error("unable to parse timestamp `%s` into ASN.1 GENERALIZEDTIME: %s", timestamp, e) 111 | raise VaultCAError("unable to parse certificate expire date") 112 | 113 | def _load_certificate(self, certificate_path): 114 | """ 115 | Load certificate or CA from disk. 116 | 117 | :param certificate_path: certificate path on disk 118 | :type certificate_path: str 119 | 120 | :return: the loaded certificate 121 | :rtype: OpenSSL.crypto.X509 122 | 123 | :raises VaultCAError: if the certificate is not loadable 124 | """ 125 | with open(certificate_path, 'r') as pem: 126 | try: 127 | certificate = load_certificate(FILETYPE_PEM, pem.read()) 128 | except Error as e: 129 | logging.error("unable to load certificate `%s`: %s", certificate_path, e) 130 | raise VaultCAError("unable to load certificate `{}`".format(certificate_path)) 131 | else: 132 | return certificate 133 | 134 | def _is_certificate_valid(self, certificate_path): 135 | """ 136 | Check if a certificate or CA is still valid. 137 | 138 | The check is done comparing the notValidAfter date of the certificate with a day in the future, 139 | based on `self.valid_interval` parameters. 140 | 141 | If the certificate is due to expire less than `self.valid_interval` days, it is marked it to be renewed. 142 | 143 | :param certificate_path: certificate path on disk 144 | :type certificate_path: str 145 | 146 | :return: certificate is valid or not 147 | :rtype: bool 148 | """ 149 | if os.path.exists(certificate_path): 150 | certificate = self._load_certificate(certificate_path) 151 | valid_not_after = self._parse_asn1_generalizedtime(certificate.get_notAfter().decode('utf-8')) 152 | if (valid_not_after - datetime.now()) < timedelta(days=self.valid_interval): 153 | logging.debug( 154 | "certificate `%s` is expiring in less than %d days, renewing required", certificate_path, 155 | self.valid_interval 156 | ) 157 | return False 158 | else: 159 | logging.debug( 160 | "certificate `%s` is expiring in more than %d days, skipping renewal", certificate_path, 161 | self.valid_interval 162 | ) 163 | return True 164 | else: 165 | logging.debug("certificate `%s` does not exist on disk, fetching required", certificate_path) 166 | return False 167 | 168 | def _write_files(self, common_name, cert_data, cert_file, priv_key_data, priv_key_file, ca_data, ca_file): 169 | """ 170 | Store certificate, private key and CA on disk, if the ones already found on disk are not valid anymore. 171 | 172 | :param common_name: common name for the certificate / key pair 173 | :type common_name: str 174 | :param cert_data: certificate data 175 | :type cert_data: str 176 | :param cert_file: certificate path on disk 177 | :type cert_file: str 178 | :param priv_key_data: private key data 179 | :type priv_key_data: str 180 | :param priv_key_file: private key path on disk 181 | :type priv_key_file: str 182 | :param ca_data: CA data 183 | :type ca_data: str 184 | :param ca_file: CA path on disk 185 | :type ca_file: str 186 | """ 187 | if not self._is_certificate_valid(cert_file): 188 | with open(cert_file, 'w') as cert, open(priv_key_file, 'w') as priv_key: 189 | logging.debug("writing certificate for %s on %s", common_name, cert_file) 190 | cert.write(cert_data) 191 | 192 | logging.debug("writing private key for %s on %s", common_name, priv_key_file) 193 | priv_key.write(priv_key_data) 194 | 195 | if self.bootstrap_ca and not self._is_certificate_valid(ca_file): 196 | with open(ca_file, 'w') as ca: 197 | logging.debug("writing CA on %s", ca_file) 198 | ca.write(ca_data) 199 | 200 | def _prepare_json_data(self, common_name, ip_sans=None, alt_names=None, ttl=None): 201 | """ 202 | Prepare the json payload to be sent to Vault with the new certificate request. 203 | 204 | :param common_name: common name for the certificate / key pair 205 | :type common_name: str 206 | :param ip_sans: list of IP for the current certificate, comma separated 207 | :type ip_sans: str 208 | :param alt_names: list of alternative names for the current certificate, comma separated 209 | :type alt_names: str 210 | :param ttl: TTL for the certificate / key pair 211 | :type ttl: str 212 | 213 | :return: json encoded payload 214 | :rtype: str 215 | """ 216 | if not ttl: 217 | ttl = self.DEFAULT_CERTIFICATE_TTL 218 | 219 | data = {'common_name': common_name, 'ttl': ttl} 220 | 221 | if ip_sans: 222 | data['ip_sans'] = ip_sans 223 | 224 | if alt_names: 225 | data['alt_names'] = alt_names 226 | 227 | logging.debug( 228 | "requesting new cert / key part for CA domain: `%s`, component: `%s`, common_name: `%s`, ip_sans: `%s`, " 229 | "alt_names: `%s`, ttl: `%s`", self.domain, self.component, common_name, ip_sans, alt_names, ttl 230 | ) 231 | 232 | return json.dumps(data) 233 | 234 | def _analise_response(self, response): 235 | """ 236 | Analise response from Vault to find errors and extract the json response payload. 237 | 238 | :type reponse: vault HTTP response 239 | :type response: requests.models.Response 240 | 241 | :return: json response payload 242 | :rtype: dict 243 | 244 | :raises VaultCAError: if HTTP code is not ok or there are errors 245 | """ 246 | if response.ok: 247 | try: 248 | payload = response.json() 249 | except json.JSONDecodeError as e: 250 | logging.error("error decoding json response: %s", e) 251 | raise VaultCAError("error decoding json response") 252 | else: 253 | errors = payload.get('errors') 254 | if errors: 255 | logging.error("vault returned errors generating cert / key pair: %s", " ".join(errors)) 256 | raise VaultCAError("vault returned errors generating cert / key pair") 257 | else: 258 | return payload 259 | else: 260 | logging.error("vault returned HTTP code `%s`", response.status_code) 261 | raise VaultCAError("vault returned HTTP error") 262 | 263 | def _extract_certificates(self, payload): 264 | """ 265 | Extract certificate, private key and CA from Vault response. 266 | 267 | :param payload: json response payload 268 | :type payload: dict 269 | :return: certificate, private key and CA 270 | :rtype: tuple 271 | 272 | :raises VaultCAError: if certificate or private key or CA are missing 273 | """ 274 | 275 | cert_data = payload.get('data', {}).get('certificate') 276 | if not cert_data: 277 | logging.error("vault payload is missing certificate data") 278 | raise VaultCAError("vault payload is missing certificate data") 279 | 280 | priv_key_data = payload.get('data', {}).get('private_key') 281 | if not priv_key_data: 282 | logging.error("vault payload is missing private key data") 283 | raise VaultCAError("vault payload is missing private key data") 284 | 285 | ca_data = payload.get('data', {}).get('issuing_ca') 286 | if not ca_data: 287 | logging.error("vault payload is missing CA data") 288 | raise VaultCAError("vault payload is missing CA data") 289 | 290 | return cert_data, priv_key_data, ca_data 291 | 292 | def fetch(self, common_name, ip_sans=None, alt_names=None, ttl=None): 293 | """ 294 | Fetch new certificate / key pair from Vault. 295 | 296 | If attribute `self.bootstrap_ca` is set to True, also the CA is fetched. 297 | 298 | Fetched object are written on disk. 299 | 300 | :param common_name: common name for the certificate / key pair 301 | :type common_name: str 302 | :param ip_sans: list of IP for the current certificate, comma separated 303 | :type ip_sans: str 304 | :param alt_names: list of alternative names for the current certificate, comma separated 305 | :type alt_names: str 306 | :param ttl: TTL for the certificate / key pair 307 | 308 | :raises VaultCAError: if the request return errors 309 | """ 310 | self._make_dirs(self.output_dir) 311 | self._make_dirs(self.ca_path) 312 | 313 | cert_file = os.path.join(self.output_dir, '{}-{}.pem'.format(self.component, common_name)) 314 | priv_key_file = os.path.join(self.output_dir, '{}-{}.key'.format(self.component, common_name)) 315 | ca_file = os.path.join(self.ca_path, "{}.crt".format(self.component)) 316 | 317 | if not self._is_certificate_valid(cert_file) or not self._is_certificate_valid(ca_file): 318 | url = "{}/{}".format(self.vault_address, self.VAULT_PATH.format(self.domain)) 319 | logging.debug("request url is `%s`", url) 320 | 321 | headers = {'X-Vault-Token': self.vault_token} 322 | data = self._prepare_json_data(common_name, ip_sans=ip_sans, alt_names=alt_names, ttl=ttl) 323 | 324 | try: 325 | response = requests.put(url, data=data, headers=headers, verify=self.ssl_verify) 326 | except requests.exceptions.RequestException as e: 327 | logging.error("exception connecting to vault endpoint: %s", e) 328 | raise VaultCAError("exception connecting to vault endpoint") 329 | else: 330 | payload = self._analise_response(response) 331 | 332 | cert_data, priv_key_data, ca_data = self._extract_certificates(payload) 333 | self._write_files(common_name, cert_data, cert_file, priv_key_data, priv_key_file, ca_data, ca_file) 334 | --------------------------------------------------------------------------------