pax_global_header00006660000000000000000000000064131046343630014515gustar00rootroot0000000000000052 comment=6019cd361df693b963f16a6e7e8aad8d2be50be0 custodia-0.5.0/000077500000000000000000000000001310463436300133325ustar00rootroot00000000000000custodia-0.5.0/.coveragerc000066400000000000000000000005361310463436300154570ustar00rootroot00000000000000[run] branch = True source = custodia tests [paths] source = src/custodia .tox/*/lib/python*/site-packages/custodia [report] ignore_errors = False precision = 1 exclude_lines = pragma: no cover raise AssertionError raise NotImplementedError if 0: if False: if __name__ == .__main__.: if PY3 if not PY3 custodia-0.5.0/.dockerignore000066400000000000000000000001601310463436300160030ustar00rootroot00000000000000# exclude all * # include wheels !dist/custodia*.whl # include Docker helpers !contrib/docker !contrib/config custodia-0.5.0/.gitignore000066400000000000000000000002641310463436300153240ustar00rootroot00000000000000/build/ /dist/ /docs/build /tests/tmp /src/*.egg-info __pycache__ *.pyc *.pyo cscope.out .tox .cache .coverage .coverage.* MANIFEST custodia.audit.log secrets.db server_socket vol custodia-0.5.0/.travis.yml000066400000000000000000000013531310463436300154450ustar00rootroot00000000000000sudo: false language: python cache: pip addons: apt: packages: - enchant matrix: include: - python: 2.7 env: TOXENV=py27 - python: 3.4 env: TOXENV=py34 - python: 3.5 env: TOXENV=py35 - python: 3.6 env: TOXENV=py36 - python: 3.5 env: TOXENV=doc - python: 3.5 env: TOXENV=lint - python: 2.7 env: TOXENV=pep8py2 - python: 3.5 env: TOXENV=pep8py3 install: - pip install --upgrade pip - pip install --upgrade setuptools - pip --version - pip install --upgrade codecov tox - tox --version script: - tox after_success: - python -m coverage combine - codecov after_failure: - test -f tests/tmp/test_log.txt && cat tests/tmp/test_log.txt custodia-0.5.0/API.md000066400000000000000000000155471310463436300143010ustar00rootroot00000000000000Custodia API ============ Custodia uses a RESTful interface to give access to secrets. Authentication and authorization are fully pluggable and are therefore, not standardized. Access paths are also not standardized, although the common practice is to mount the secrets api under the /secrets URI The Custodia API uses JSON to format requests and replies. Key/Request formats =================== A key is a dictionary that contains the 'type' and 'value' of a key. Simple ------ Format: { type: "simple", value: } The Simple type is an arbitrary value holder. It is recommend but not required to base64 encode binary values or non-string values. The value must be representable as a valid JSON string. Keys are validated before being stored, unknown key types or invalid JSON values are refused and an error is returned. NOTE: As an alternative it is possible to send a simple "raw" value by setting the Content-type of the request to "application/octet-stream". In this case the value will be base64 encoded when received and can be accessed as a base64 encoded value in the JSON string when the default GET format is used. Sending the "Accept: application/octet-stream" header will instead cause the GET operation to return just the raw value that was originally sent. Key Exchange Message -------------------- the Key Exchange Message format builds on the JSON Web Signature and the JSON Web Encryption specification to build respectively the request and reply messages. The aim is to provide the Custodia server the means to encrypt the reply to a client that proves possession of private key. Format: - Query arguments for GET: type=kem value=Message - JSON Value for PUT/GET Reply: {"type:"kem","value":"Message"} The Message for a GET is a JWT (JWS): (flattened/decoded here for clarity) { "protected": { "kid": , "alg": "a valid alg name"}, "claims": { "sub": , "exp": , ["value": ]}, "signature": "XYZ...." } Attributes: - public-key-identifier: This is the kid of a key that must be known to the Custodia service. If opportunistic encryption is desired, and the requesting client is authenticated in other ways a "jku" header could be used instead, and a key fetched on the fly. This is not recommended for the general case and is not currently supported by the implementation. - name-of-secret: this repeats the name of the secret embedded in the GET, This is used to prevent substitution attacks where a client is intercepted and its signed request is reused to request a different key. - unix-timestamp: used to limit replay attacks, indicated expiration time, and should be no further than 5 minutes in the future, with leeway up to 10 minutes to account for clock skews Additional claims may be present, for example a 'value'. The Message for a GET reply or a PUT is a JWS Encoded message (see above) nested in a JWE Encoded message: (flattened/decoded here for clarity): { "protected": { "kid": , "alg": "a valid alg name", "enc": "a valid enc type"}, "encrypted_key": , "iv": , "ciphertext": , "tag": } Attributes: - public-key-identifier: Must be the server public key identifier. reply (see above). Or the server public key for a PUT. - The inner JWS payload will typically contain a 'value' that is an arbitrary key. example: { type: "simple", value: } REST API ======== Objects ------- There are essentially 2 objects recognized by the API: - keys - key containers Key containers can be nested and named arbitrarily, however depending on authorization schemes used the basic container is often named after a group or a user in order to make authorization checks simpler. Getting keys ------------ A GET operation with the name of the key: GET /secrets/name/of/key A query parameter named 'type' can be provided, in that case the key is returned only if it matches the requested type. Returns: - 200 and a JSON formatted key in case of success. - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 if no key was found - 406 not acceptable, key type unknown/not permitted - 501 if the API is not supported Storing keys ------------ A PUT operation with the name of the key: PUT /secrets/name/of/key The Content-Type MUST be 'application/json' The Content-Length MUST be specified, and the body MUST be a key in one of the valid formats described above. Returns: - 201 in case of success. - 400 if the request format is invalid - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 one of the elements of the path is not a valid container - 405 if the target is a directory instead of a key (path ends in '/') - 406 not acceptable, key type unknown/not permitted - 409 if the key already exists - 501 if the API is not supported Deleting keys ------------- A DELETE operation with the name of the key: DELETE /secrets/name/of/key Returns: - 204 in case of success. - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 if no key was found - 406 not acceptable, type unknown/not permitted - 501 if the API is not supported Listing containers ------------------ A GET operation on a path that ends in a '/' translates into a listing for a container. GET /secrets/container/ Implementations may assume a default container if none is explicitly provided: GET /secrets/ may return only keys under //* Returns: - 200 in case of success and a dictionary containing a list of all keys in the container and all subcontainers. - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 if no key was found - 406 not acceptable, type unknown/not permitted - 501 if the API is not supported Creating containers ------------------- A POST operation on a path will create a container with that name. A trailing '/' is required POST /secrets/mycontainer/ Default containers may be automatically created by an implementation. Returns: - 201 in case of success. - 400 if the request format is invalid - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 one of the elements of the path is not a valid container - 406 not acceptable, type unknown/not permitted - 409 if the container already exists - 501 if the API is not supported Deleting containers ------------------- A DELETE operation with the name of the container: DELETE /secrets/mycontainer/ Returns: - 204 in case of success. - 401 if authentication is necessary - 403 if access to the container is forbidden - 404 if no container was found - 406 not acceptable, type unknown/not permitted - 409 if the container is not empty - 501 if the API is not supported custodia-0.5.0/LICENSE000066400000000000000000001045131310463436300143430ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . custodia-0.5.0/MANIFEST.in000066400000000000000000000007661310463436300151010ustar00rootroot00000000000000include setup.py setup.cfg include Makefile LICENSE README include *.md *.ini .coveragerc include bin/custodia bin/custodia-cli include custodia.conf recursive-include examples *.key *.db recursive-include docs *.py *.rst include docs/Makefile include man/custodia.7 recursive-include contrib *.txt *.conf *.service *.socket Dockerfile recursive-include tests *.py recursive-include tests *.conf recursive-include tests/ca *.key *.pem *.sh prune tests/tmp prune tests/ca/tmp exclude server_socket custodia-0.5.0/Makefile000066400000000000000000000126451310463436300150020ustar00rootroot00000000000000CONF := custodia.conf PREFIX := /usr PYTHON := python3 TOX := $(PYTHON) -m tox --sitepackages DOCS_DIR = docs SERVER_SOCKET = $(CURDIR)/server_socket RPMBUILD = $(CURDIR)/dist/rpmbuild VERSION ?= $(shell $(PYTHON) setup.py --quiet version) DOCKER_CMD = docker DOCKER_IMAGE = latchset/custodia DOCKER_RELEASE_ARGS = --no-cache=true --pull=true CONTAINER_NAME = custodia_container CONTAINER_VOL = $(CURDIR)/vol CONTAINER_SOCKET = $(CONTAINER_VOL)/run/sock CONTAINER_CLI = $(CONTAINER_VOL)/custodia-cli # helper script for demo define CUSTODIA_CLI_SCRIPT #!/bin/sh set -e PYTHONPATH=$(CURDIR)/src $(PYTHON) -Wignore -m custodia.cli \ --server $(CONTAINER_SOCKET) $$@ endef export CUSTODIA_CLI_SCRIPT .NOTPARALLEL: .PHONY: all clean clean_socket cscope docs lint pep8 test all: clean_socket lint pep8 test docs echo "All tests passed" clean_socket: rm -f $(SERVER_SOCKET) $(CONTAINER_SOCKET) clean_coverage: rm -f .coverage .coverage.* lint: clean_socket $(TOX) -e lint pep8: clean_socket $(TOX) -e pep8py2 $(TOX) -e pep8py3 clean: clean_socket clean_coverage rm -fr build dist *.egg-info .tox MANIFEST .cache rm -f custodia.audit.log secrets.db rm -rf docs/build find ./ -name '*.py[co]' -exec rm -f {} \; find ./ -depth -name __pycache__ -exec rm -rf {} \; rm -rf tests/tmp rm -rf vol cscope: git ls-files | xargs pycscope test: clean_socket clean_coverage $(TOX) --skip-missing-interpreters -e py27 $(TOX) --skip-missing-interpreters -e py34 $(TOX) --skip-missing-interpreters -e py35 $(TOX) --skip-missing-interpreters -e py36 $(TOX) --skip-missing-interpreters -e doc $(TOX) -e coverage-report README: README.md echo -e '.. WARNING: AUTO-GENERATED FILE. DO NOT EDIT.\n' > $@ pandoc --from=markdown --to=rst $< >> $@ $(DOCS_DIR)/source/readme.rst: README grep -ve '^|Build Status|' < $< | grep -v travis-ci.org > $@ docs: $(DOCS_DIR)/source/readme.rst sort $(DOCS_DIR)/source/spelling_wordlist.txt > \ $(DOCS_DIR)/source/spelling_wordlist.txt.bak mv $(DOCS_DIR)/source/spelling_wordlist.txt.bak \ $(DOCS_DIR)/source/spelling_wordlist.txt PYTHONPATH=$(CURDIR)/src \ $(MAKE) -C $(DOCS_DIR) html SPHINXBUILD="$(PYTHON) -m sphinx" .PHONY: install egg_info run packages release releasecheck install: clean_socket egg_info $(PYTHON) setup.py install --root "$(PREFIX)" install -d "$(PREFIX)/share/man/man7" install -t "$(PREFIX)/share/man/man7" man/custodia.7 install -d "$(PREFIX)/share/doc/custodia/examples" install -t "$(PREFIX)/share/doc/custodia" LICENSE README API.md install -t "$(PREFIX)/share/doc/custodia/examples" custodia.conf egg_info: $(PYTHON) setup.py egg_info packages: egg_info README $(PYTHON) setup.py packages cd dist && for F in *.gz; do sha512sum $${F} > $${F}.sha512sum.txt; done release: clean @echo "dnf install python3-wheel python3-twine" $(MAKE) packages @echo -e "\nCustodia release" @echo -e "----------------\n" @echo "* Upload all release files to github:" @echo " $$(find dist -type f -printf '%p ')" @echo "* Upload source dist and wheel to PyPI:" @echo " twine-3 upload dist/*.gz dist/*.whl" releasecheck: clean @ # ensure README is rebuild touch README.md $(MAKE) README $(DOCS_DIR)/source/readme.rst @ # check for version in spec grep -q 'version $(VERSION)' custodia.spec || exit 1 @ # re-run tox tox -r $(MAKE) packages $(MAKE) rpm $(MAKE) dockerbuild run: egg_info $(PYTHON) $(CURDIR)/bin/custodia $(CONF) .PHONY: rpmroot rpmfiles rpm rpmroot: mkdir -p $(RPMBUILD)/BUILD mkdir -p $(RPMBUILD)/RPMS mkdir -p $(RPMBUILD)/SOURCES mkdir -p $(RPMBUILD)/SPECS mkdir -p $(RPMBUILD)/SRPMS rpmfiles: rpmroot packages mv dist/custodia-$(VERSION).tar.gz* $(RPMBUILD)/SOURCES cp contrib/config/custodia/custodia.conf $(RPMBUILD)/SOURCES/ cp contrib/config/systemd/system/custodia@.service $(RPMBUILD)/SOURCES/ cp contrib/config/systemd/system/custodia@.socket $(RPMBUILD)/SOURCES/ cp contrib/config/tmpfiles.d/custodia.conf $(RPMBUILD)/SOURCES/custodia.tmpfiles.conf rpm: clean rpmfiles egg_info rpmbuild \ --define "_topdir $(RPMBUILD)" \ --define "version $(VERSION)" \ -ba custodia.spec echo "$(RPMBUILD)/RPMS" .PHONY: dockerbuild dockerdemo dockerdemoinit dockershell dockerreleasebuild dockerbuild: rm -f dist/custodia*.whl $(PYTHON) setup.py bdist_wheel $(DOCKER_CMD) build $(DOCKER_BUILD_ARGS) \ -f contrib/docker/Dockerfile \ -t $(DOCKER_IMAGE) . dockerdemo: dockerbuild @mkdir -p -m755 $(CONTAINER_VOL)/lib $(CONTAINER_VOL)/log $(CONTAINER_VOL)/run @echo "$$CUSTODIA_CLI_SCRIPT" > $(CONTAINER_CLI) @chmod 755 $(CONTAINER_CLI) @echo "Custodia CLI: $(CONTAINER_CLI)" @$(DOCKER_CMD) rm $(CONTAINER_NAME) >/dev/null 2>&1|| true $(DOCKER_CMD) run \ --name $(CONTAINER_NAME) \ --user $(shell id -u):$(shell id -g) \ -e CREDS_UID=$(shell id -u) -e CREDS_GID=$(shell id -g) \ -v $(CONTAINER_VOL)/lib:/var/lib/custodia:Z \ -v $(CONTAINER_VOL)/log:/var/log/custodia:Z \ -v $(CONTAINER_VOL)/run:/var/run/custodia:Z \ $(DOCKER_IMAGE):latest \ /usr/bin/custodia /etc/custodia/demo.conf dockerdemoinit: $(CONTAINER_VOL)/custodia-cli mkdir /container $(CONTAINER_VOL)/custodia-cli set /container/key value $(CONTAINER_VOL)/custodia-cli get /container/key dockershell: $(DOCKER_CMD) exec -ti $(CONTAINER_NAME) /bin/bash dockerreleasebuild: $(MAKE) dockerbuild \ DOCKER_BUILD_ARGS="$(DOCKER_RELEASE_ARGS)" \ DOCKER_IMAGE="$(DOCKER_IMAGE):$(VERSION)" && \ echo -e "\n\nRun: $(DOCKER_CMD) push $(DOCKER_IMAGE):$(VERSION)" custodia-0.5.0/README000066400000000000000000000026631310463436300142210ustar00rootroot00000000000000.. WARNING: AUTO-GENERATED FILE. DO NOT EDIT. |Build Status| Custodia ======== A tool for managing secrets. See our `Quick Start Guide `__ Custodia is a project that aims to define an API for modern cloud applications that allows to easily store and share passwords, tokens, certificates and any other secret in a way that keeps data secure, manageable and auditable. The Custodia project offers example implementations of clear text and encrypted backends, and aims to soon provide drivers to store data in external data stores like the Vault Project, OpenStack's Barbican, FreeIPA's Vault and similar. In future the Custodia project plans to enhance and enrich the API to provide access to even more secure means of dealing with private keys, like HSM as a Service and other similar security systems. See the Custodia documentation for more information: https://custodia.readthedocs.io Requirements ------------ Runtime ~~~~~~~ - configparser (Python 2.7) - cryptography - jwcrypto >= 0.2 - requests - six Installation and testing ~~~~~~~~~~~~~~~~~~~~~~~~ - pip - setuptools >= 18.0 - tox >= 2.3.1 - wheel API stability ------------- Some APIs are provisional and may change in the future. - Command line interface in module ``custodia.cli``. - The script custodia-cli. .. |Build Status| image:: https://travis-ci.org/latchset/custodia.svg?branch=master :target: https://travis-ci.org/latchset/custodia custodia-0.5.0/README.md000066400000000000000000000024421310463436300146130ustar00rootroot00000000000000[![Build Status](https://travis-ci.org/latchset/custodia.svg?branch=master)](https://travis-ci.org/latchset/custodia) # Custodia A tool for managing secrets. See our [Quick Start Guide](docs/source/quick.rst) Custodia is a project that aims to define an API for modern cloud applications that allows to easily store and share passwords, tokens, certificates and any other secret in a way that keeps data secure, manageable and auditable. The Custodia project offers example implementations of clear text and encrypted backends, and aims to soon provide drivers to store data in external data stores like the Vault Project, OpenStack's Barbican, FreeIPA's Vault and similar. In future the Custodia project plans to enhance and enrich the API to provide access to even more secure means of dealing with private keys, like HSM as a Service and other similar security systems. See the Custodia documentation for more information: https://custodia.readthedocs.io ## Requirements ### Runtime * configparser (Python 2.7) * cryptography * jwcrypto >= 0.2 * requests * six ### Installation and testing * pip * setuptools >= 18.0 * tox >= 2.3.1 * wheel ## API stability Some APIs are provisional and may change in the future. * Command line interface in module ```custodia.cli```. * The script custodia-cli. custodia-0.5.0/bin/000077500000000000000000000000001310463436300141025ustar00rootroot00000000000000custodia-0.5.0/bin/custodia000077500000000000000000000012661310463436300156500ustar00rootroot00000000000000#!/usr/bin/python2.7 import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) SRC = os.path.join(os.path.dirname(HERE), 'src') sys.path.insert(0, SRC) def main(dist='custodia', group='console_scripts', name='custodia'): # delay pkg_resources after sys.path changes import pkg_resources pkg_resources.working_set.add_entry(SRC) ep = pkg_resources.get_entry_info(dist, group, name) if os.path.normpath(ep.dist.location) != os.path.normpath(SRC): raise RuntimeError(ep.dist.location) if hasattr(ep, 'resolve'): func = ep.resolve() else: func = ep.load(require=False) sys.exit(func()) if __name__ == '__main__': main() custodia-0.5.0/bin/custodia-cli000077500000000000000000000012721310463436300164120ustar00rootroot00000000000000#!/usr/bin/python2.7 import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) SRC = os.path.join(os.path.dirname(HERE), 'src') sys.path.insert(0, SRC) def main(dist='custodia', group='console_scripts', name='custodia-cli'): # delay pkg_resources after sys.path changes import pkg_resources pkg_resources.working_set.add_entry(SRC) ep = pkg_resources.get_entry_info(dist, group, name) if os.path.normpath(ep.dist.location) != os.path.normpath(SRC): raise RuntimeError(ep.dist.location) if hasattr(ep, 'resolve'): func = ep.resolve() else: func = ep.load(require=False) sys.exit(func()) if __name__ == '__main__': main() custodia-0.5.0/contrib/000077500000000000000000000000001310463436300147725ustar00rootroot00000000000000custodia-0.5.0/contrib/config/000077500000000000000000000000001310463436300162375ustar00rootroot00000000000000custodia-0.5.0/contrib/config/README.txt000066400000000000000000000010511310463436300177320ustar00rootroot00000000000000Example configuration and systemd service ========================================= Install: groupadd -r custodia useradd -r -g custodia -d /var/lib/custodia -s /bin/false -c "Custodia" custodia cp tmpfiles.d/custodia.conf /etc/tmpfiles.d/ systemd-tmpfiles --create install -d -m 750 -o custodia -g custodia /etc/custodia /var/log/custodia /var/lib/custodia cp custodia/custodia.conf /etc/custodia/ cp systemd/system/custodia.* /etc/systemd/system/ systemctl daemon-reload systemctl enable --now custodia.socket custodia-0.5.0/contrib/config/custodia/000077500000000000000000000000001310463436300200525ustar00rootroot00000000000000custodia-0.5.0/contrib/config/custodia/custodia.conf000066400000000000000000000010051310463436300225300ustar00rootroot00000000000000# /etc/custodia/custodia.conf [global] debug = true makedirs = true [store:sqlite] handler = SqliteStore dburi = ${libdir}/secrets.db table = secrets [store:encrypted_sqlite] handler = EncryptedOverlay backing_store = sqlite master_key = ${libdir}/secrets.key master_enctype = A128CBC-HS256 autogen_master_key = true [auth:creds] handler = SimpleCredsAuth uid = root gid = root [authz:paths] handler = SimplePathAuthz paths = /. /secrets [/] handler = Root [/secrets] handler = Secrets store = encrypted_sqlite custodia-0.5.0/contrib/config/systemd/000077500000000000000000000000001310463436300177275ustar00rootroot00000000000000custodia-0.5.0/contrib/config/systemd/system/000077500000000000000000000000001310463436300212535ustar00rootroot00000000000000custodia-0.5.0/contrib/config/systemd/system/custodia@.service000066400000000000000000000006241310463436300245520ustar00rootroot00000000000000# /etc/systemd/system/custodia@.service [Unit] Description=Custodia Secrets Service for %I Documentation=https://github.com/latchset/custodia Requires=custodia@%i.socket After=network.target [Service] Type=notify ExecStart=/usr/sbin/custodia --instance=%i /etc/custodia/%i.conf User=custodia Group=custodia ProtectSystem=full ProtectHome=true NoNewPrivileges=true [Install] WantedBy=multi-user.target custodia-0.5.0/contrib/config/systemd/system/custodia@.socket000066400000000000000000000005001310463436300243730ustar00rootroot00000000000000# /etc/systemd/system/custodia@.socket [Unit] Description=Custodia Socket for %i Documentation=https://github.com/latchset/custodia [Socket] ListenStream=/var/run/custodia/%i.sock Service=custodia@%i.service RemoveOnStop=true SocketUser=custodia SocketGroup=custodia SocketMode=0666 [Install] WantedBy=sockets.target custodia-0.5.0/contrib/config/tmpfiles.d/000077500000000000000000000000001310463436300203045ustar00rootroot00000000000000custodia-0.5.0/contrib/config/tmpfiles.d/custodia.conf000066400000000000000000000000471310463436300227670ustar00rootroot00000000000000d /run/custodia 0755 custodia custodia custodia-0.5.0/contrib/docker/000077500000000000000000000000001310463436300162415ustar00rootroot00000000000000custodia-0.5.0/contrib/docker/Dockerfile000066400000000000000000000023011310463436300202270ustar00rootroot00000000000000FROM fedora:25 MAINTAINER Christian Heimes RUN dnf -y update && dnf clean all # install Custodia dependencies RUN dnf -y install \ python3 python3-pip python3-wheel \ python3-requests python3-six python3-jwcrypto \ && dnf clean all # Create Custodia user and group # sum(ord(c) for c in 'cust') == 447 RUN groupadd -r custodia -g ${CUSTODIA_GID:-447} \ && useradd -u ${CUSTODIA_GID:-447} -r -g custodia -d /var/lib/custodia -s /bin/bash -c "Custodia" custodia # Directories RUN install -d -m 755 -o custodia -g custodia \ /etc/custodia \ /var/log/custodia \ /var/run/custodia \ /var/lib/custodia VOLUME ["/etc/custodia", "/var/log/custodia", "/var/lib/custodia", "/var/run/custodia"] # Copy default custodia conf COPY contrib/config/custodia/custodia.conf /etc/custodia/ COPY contrib/docker/demo.conf /etc/custodia/ RUN chown custodia:custodia /etc/custodia/*.conf \ && chmod 644 /etc/custodia/*.conf CMD ["/usr/bin/custodia", "/etc/custodia/custodia.conf"] # Copy and install wheel package COPY dist/custodia*.whl /tmp RUN pip3 install --disable-pip-version-check --no-cache-dir --no-deps \ --upgrade --pre /tmp/custodia*.whl USER custodia custodia-0.5.0/contrib/docker/demo.conf000066400000000000000000000012501310463436300200320ustar00rootroot00000000000000# /etc/custodia/custodia.conf [DEFAULT] libdir = /var/lib/custodia logdir = /var/log/custodia rundir = /var/run/custodia [global] debug = true server_socket = ${rundir}/sock auditlog = ${logdir}/audit.log [store:sqlite] handler = SqliteStore dburi = ${libdir}/secrets.db table = secrets [store:encrypted_sqlite] handler = EncryptedOverlay backing_store = sqlite master_key = ${libdir}/secrets.key master_enctype = A128CBC-HS256 autogen_master_key = true [auth:creds] handler = SimpleCredsAuth uid = ${ENV:CREDS_UID} gid = ${ENV:CREDS_GID} [authz:paths] handler = SimplePathAuthz paths = /. /secrets [/] handler = Root [/secrets] handler = Secrets store = encrypted_sqlite custodia-0.5.0/custodia.conf000066400000000000000000000052021310463436300160130ustar00rootroot00000000000000# This config file supports extended interpolations # https://docs.python.org/3/library/configparser.html#configparser.ExtendedInterpolation # Environment variables can be references from the ENV section: # # Example: # [DEFAULT] # cafile = 'path/to/ca.pem' # [global] # tls_cafile = ${DEFAULT:cafile} # server_socket = ${ENV:HOME}/server_socket [global] server_version = "Secret/0.0.7" debug = True #server_url = https://0.0.0.0:10443 server_socket = ./server_socket auditlog = ${configdir}/custodia.audit.log tls_certfile = tests/ca/custodia-server.pem tls_keyfile = tests/ca/custodia-server.key tls_cafile = tests/ca/custodia-ca.pem tls_verify_client = true umask = 027 #[auth:simple] #handler = SimpleCredsAuth #uid = 48 #gid = 48 [auth:header] handler = SimpleHeaderAuth header = REMOTE_USER [authz:paths] handler = SimplePathAuthz paths = /. [authz:namespaces] handler = UserNameSpace path = /secrets/ store = simple [store:simple] handler = SqliteStore dburi = secrets.db table = secrets filemode = 640 [/] handler = Root store = simple # Multi-tenant example [store:tenant1] handler = SqliteStore dburi = secrets.db table = tenant1 [authz:tenant1] handler = UserNameSpace path = /tenant1/secrets/ store = tenant1 [/tenant1/secrets] handler = Secrets store = tenant1 # Encstore example [store:encrypted] handler = EncryptedStore dburi = examples/enclite.db table = enclite master_key = examples/enclite.sample.key master_enctype = A128CBC-HS256 [auth:sak] handler = SimpleAuthKeys store = encrypted # sample key: test=foo-host-key [authz:encrypted] handler = UserNameSpace path = /enc/secrets/ store = encrypted [store:kemkeys] handler = EncryptedStore dburi = examples/enclite.db table = enclite master_key = examples/enclite.sample.key master_enctype = A128CBC-HS256 [authz:kkstore] handler = KEMKeysStore path = /enc/secrets/ store = kemkeys [/enc/secrets] handler = Secrets allowed_keytypes = simple kem store = encrypted # Forward [authz:forwarders] handler = SimplePathAuthz paths = /forwarder /forwarder_loop [/forwarder] handler = Forwarder forward_uri = http+unix://%2e%2fserver_socket/secrets forward_headers = {"CUSTODIA_AUTH_ID": "test", "CUSTODIA_AUTH_KEY": "foo-host-key"} [/forwarder_loop] handler = Forwarder forward_uri = http+unix://%2e%2fserver_socket/forwarder_loop forward_headers = {"REMOTE_USER": "test"} # Encgen example [store:backing] handler = SqliteStore dburi = examples/enclite.db table = enclite [store:overlay] handler = EncryptedOverlay backing_store = backing master_key = examples/enclite.sample.key master_enctype = A128CBC-HS256 [authz:kemgen] handler = KEMKeysStore path = /encgen/secrets/ store = overlay custodia-0.5.0/custodia.spec000066400000000000000000000203101310463436300160150ustar00rootroot00000000000000%if 0%{?fedora} %global with_python3 1 %global with_etcdstore 1 %endif %{!?version: %define version 0.5.dev1} Name: custodia Version: %{version} Release: 3%{?dist} Summary: A service to manage, retrieve and store secrets for other processes License: GPLv3+ URL: https://github.com/latchset/%{name} Source0: https://github.com/latchset/%{name}/releases/download/v%{version}/%{name}-%{version}.tar.gz Source1: https://github.com/latchset/%{name}/releases/download/v%{version}/%{name}-%{version}.tar.gz.sha512sum.txt Source2: custodia.conf Source3: custodia@.service Source4: custodia@.socket Source5: custodia.tmpfiles.conf BuildArch: noarch BuildRequires: systemd BuildRequires: python2-devel BuildRequires: python-jwcrypto BuildRequires: python2-requests BuildRequires: python2-setuptools >= 18 BuildRequires: python2-coverage BuildRequires: python-tox >= 2.3.1 BuildRequires: python2-pytest BuildRequires: python-docutils BuildRequires: python2-configparser BuildRequires: python2-systemd %if 0%{?with_etcdstore} BuildRequires: python2-python-etcd %endif %if 0%{?with_python3} BuildRequires: python3-devel BuildRequires: python3-jwcrypto BuildRequires: python3-requests BuildRequires: python3-setuptools > 18 BuildRequires: python3-coverage BuildRequires: python3-tox >= 2.3.1 BuildRequires: python3-pytest BuildRequires: python3-python-etcd BuildRequires: python3-docutils BuildRequires: python3-systemd %endif Requires(pre): shadow-utils Requires(preun): systemd-units Requires(postun): systemd-units Requires(post): systemd-units %if 0%{?with_python3} Requires: python3-custodia = %{version}-%{release} %else Requires: python2-custodia = %{version}-%{release} %endif %global overview \ Custodia is a Secrets Service Provider, it stores or proxies access to \ keys, password, and secret material in general. Custodia is built to \ use the HTTP protocol and a RESTful API as an IPC mechanism over a local \ Unix Socket. It can also be exposed to a network via a Reverse Proxy \ service assuming proper authentication and header validation is \ implemented in the Proxy. \ \ Custodia is modular, the configuration file controls how authentication, \ authorization, storage and API plugins are combined and exposed. %description A service to manage, retrieve and store secrets for other processes %{overview} %package -n python2-custodia Summary: Sub-package with python2 custodia modules Provides: python-custodia = %{version}-%{release} Obsoletes: python-custodia <= 0.1.0 Requires: python2-configparser Requires: python-jwcrypto Requires: python2-requests Requires: python2-setuptools Requires: python2-systemd %description -n python2-custodia Sub-package with python custodia modules %{overview} %if 0%{?with_etcdstore} %package -n python2-custodia-etcdstore Summary: Sub-package with python2 custodia etcdstore Requires: python2-python-etcd Requires: python2-custodia = %{version}-%{release} Obsoletes: python2-custodia-extras <= 0.3.1 %description -n python2-custodia-etcdstore Sub-package with python2 custodia etcdstore plugin %{overview} %endif # with_etcdstore %if 0%{?with_python3} %package -n python3-custodia Summary: Sub-package with python3 custodia modules Requires: python3-jwcrypto Requires: python3-requests Requires: python3-setuptools Requires: python3-systemd %description -n python3-custodia Sub-package with python custodia modules %{overview} %if 0%{?with_etcdstore} %package -n python3-custodia-etcdstore Summary: Sub-package with python3 custodia etcdstoore Requires: python3-python-etcd Requires: python3-custodia = %{version}-%{release} Obsoletes: python3-custodia-extras <= 0.3.1 %description -n python3-custodia-etcdstore Sub-package with python3 custodia extra etcdstore plugin %{overview} %endif # with_etcdstore %endif # with_python3 %prep grep `sha512sum %{SOURCE0}` %{SOURCE1} || (echo "Checksum invalid!" && exit 1) %autosetup %build %{__python2} setup.py egg_info build %if 0%{?with_python3} %{__python3} setup.py egg_info build %endif %check # don't download packages export PIP_INDEX_URL=http://host.invalid./ # Don't try to download dnspython3. The package is provided by python3-dns export PIP_NO_DEPS=yes tox --sitepackages -e py27 -- --skip-servertests %if 0%{?with_python3} TOXENV=$(%{__python3} -c 'import sys; print("py{0.major}{0.minor}".format(sys.version_info))') tox --sitepackages -e $TOXENV -- --skip-servertests %endif %install mkdir -p %{buildroot}/%{_sbindir} mkdir -p %{buildroot}/%{_mandir}/man7 mkdir -p %{buildroot}/%{_defaultdocdir}/custodia mkdir -p %{buildroot}/%{_defaultdocdir}/custodia/examples mkdir -p %{buildroot}/%{_sysconfdir}/custodia mkdir -p %{buildroot}/%{_unitdir} mkdir -p %{buildroot}/%{_tmpfilesdir} mkdir -p %{buildroot}/%{_localstatedir}/lib/custodia mkdir -p %{buildroot}/%{_localstatedir}/log/custodia mkdir -p %{buildroot}/%{_localstatedir}/run/custodia %{__python2} setup.py install --skip-build --root %{buildroot} mv %{buildroot}/%{_bindir}/custodia %{buildroot}/%{_sbindir}/custodia cp %{buildroot}/%{_sbindir}/custodia %{buildroot}/%{_sbindir}/custodia-2 cp %{buildroot}/%{_bindir}/custodia-cli %{buildroot}/%{_bindir}/custodia-cli-2 install -m 644 -t "%{buildroot}/%{_mandir}/man7" man/custodia.7 install -m 644 -t "%{buildroot}/%{_defaultdocdir}/custodia" README API.md install -m 644 -t "%{buildroot}/%{_defaultdocdir}/custodia/examples" custodia.conf install -m 600 %{SOURCE2} %{buildroot}%{_sysconfdir}/custodia install -m 644 %{SOURCE3} %{buildroot}%{_unitdir} install -m 644 %{SOURCE4} %{buildroot}%{_unitdir} install -m 644 %{SOURCE5} %{buildroot}%{_tmpfilesdir}/custodia.conf %if 0%{?with_python3} # overrides /usr/bin/custodia-cli and /usr/sbin/custodia with Python 3 shebang %{__python3} setup.py install --skip-build --root %{buildroot} mv %{buildroot}/%{_bindir}/custodia %{buildroot}/%{_sbindir}/custodia cp %{buildroot}/%{_sbindir}/custodia %{buildroot}/%{_sbindir}/custodia-3 cp %{buildroot}/%{_bindir}/custodia-cli %{buildroot}/%{_bindir}/custodia-cli-3 %endif %pre getent group custodia >/dev/null || groupadd -r custodia getent passwd custodia >/dev/null || \ useradd -r -g custodia -d / -s /sbin/nologin \ -c "User for custodia" custodia exit 0 %post %systemd_post custodia@\*.socket %systemd_post custodia@\*.service %preun %systemd_preun custodia@\*.socket %systemd_preun custodia@\*.service %postun %systemd_postun custodia@\*.socket %systemd_postun custodia@\*.service %files %doc README API.md %doc %{_defaultdocdir}/custodia/examples/custodia.conf %license LICENSE %{_mandir}/man7/custodia* %{_sbindir}/custodia %{_bindir}/custodia-cli %dir %attr(0700,custodia,custodia) %{_sysconfdir}/custodia %config(noreplace) %attr(600,custodia,custodia) %{_sysconfdir}/custodia/custodia.conf %attr(644,root,root) %{_unitdir}/custodia@.socket %attr(644,root,root) %{_unitdir}/custodia@.service %dir %attr(0700,custodia,custodia) %{_localstatedir}/lib/custodia %dir %attr(0700,custodia,custodia) %{_localstatedir}/log/custodia %dir %attr(0755,custodia,custodia) %{_localstatedir}/run/custodia %{_tmpfilesdir}/custodia.conf %files -n python2-custodia %license LICENSE %exclude %{python2_sitelib}/custodia/store/etcdstore.py* %{python2_sitelib}/* %{_sbindir}/custodia-2 %{_bindir}/custodia-cli-2 %if 0%{?with_etcdstore} %files -n python2-custodia-etcdstore %license LICENSE %{python2_sitelib}/custodia/store/etcdstore.py* %endif # with_etcdstore %if 0%{?with_python3} %files -n python3-custodia %license LICENSE %exclude %{python3_sitelib}/custodia/store/etcdstore.py %exclude %{python3_sitelib}/custodia/store/__pycache__/etcdstore.* %{python3_sitelib}/* %{_sbindir}/custodia-3 %{_bindir}/custodia-cli-3 %if 0%{?with_etcdstore} %files -n python3-custodia-etcdstore %license LICENSE %{python3_sitelib}/custodia/store/etcdstore.py %{python3_sitelib}/custodia/store/__pycache__/etcdstore.* %endif # with_etcdstore %endif # with_python3 custodia-0.5.0/docs/000077500000000000000000000000001310463436300142625ustar00rootroot00000000000000custodia-0.5.0/docs/Makefile000066400000000000000000000142631310463436300157300ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Custodia.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Custodia.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Custodia" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Custodia" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." custodia-0.5.0/docs/docs_requirements.txt000066400000000000000000000001031310463436300205500ustar00rootroot00000000000000# for RTFD docutils markdown docker-py python-etcd sphinx-argparse custodia-0.5.0/docs/source/000077500000000000000000000000001310463436300155625ustar00rootroot00000000000000custodia-0.5.0/docs/source/api.rst000066400000000000000000000146041310463436300170720ustar00rootroot00000000000000.. Keep in sync with API.md ============ Custodia API ============ Custodia uses a RESTful interface to give access to secrets. Authentication and authorization are fully pluggable and are therefore, not standardized. Access paths are also not standardized, although the common practice is to mount the secrets api under the /secrets URI. The Custodia API uses JSON to format requests and replies. Key/Request formats =================== A key is a dictionary that contains the 'type' and 'value' of a key. Simple ------ Format: ``{ type: "simple", value: }`` The Simple type is an arbitrary value holder. It is recommended, but not required to base64 encode binary values or non-string values. The value must be presentable as a valid JSON string. Keys are validated before being stored. Unknown key types or invalid JSON values are refused and an error is returned. NOTE: As an alternative, it is possible to send a simple "raw" value by setting the Content-type of the request to "application/octet-stream". In this case, the value will be base64 encoded when received and can be accessed as a base64 encoded value in the JSON string when the default GET operation is used. Sending the "Accept: application/octet-stream" header will instead cause the GET operation to return just the raw value that was originally sent. Key Exchange Message -------------------- The Key Exchange Message format builds on the JSON Web Signature and the JSON Web Encryption specifications to build respectively the request and reply messages. The aim is to provide the Custodia server the means to encrypt the reply to a client that proves possession of private key. Format: - Query arguments for GET: type=kem value=Message - JSON Value for PUT/GET Reply: ``{"type:"kem","value":"Message"}`` The Message for a GET is a JWT (JWS): (flattened/decoded here for clarity): ``{ "protected": { "kid": , "alg": "a valid alg name"}, "claims": { "sub": , "exp": , ["value": ]}, "signature": "XYZ...." }`` Attributes: - public-key-identifier: This is the kid of a key that must be known to the Custodia service. If opportunistic encryption is desired and the requesting client is authenticated in other ways, a "jku" header could be used instead and a key fetched on the fly. This is not recommended for the general case and is not currently supported by the implementation. - name-of-secret: this repeats the name of the secret embedded in the GET. This is used to prevent substitution attacks where a client is intercepted and its signed request is reused to request a different key. - unix-timestamp: used to limit replay attacks, indicated expiration time, and should be no further than 5 minutes in the future, with leeway up to 10 minutes to account for clock skews. - Additional claims may be present, for example a 'value'. The Message for a GET reply or a PUT is a JWS Encoded message (see above) nested in a JWE Encoded message: (flattened/decoded here for clarity): ``{ "protected": { "kid": , "alg": "a valid alg name", "enc": "a valid enc type"}, "encrypted\_key": , "iv": , "ciphertext": , "tag": }`` Attributes: - public-key-identifier: Must be the server public key identifier. reply (see above). Or the server public key for a PUT. - The inner JWS payload will typically contain a 'value' that is an arbitrary key. example: ``{ type: "simple", value: }`` REST API ======== Objects ------- There are essentially 2 objects recognized by the API: - keys - key containers Key containers can be nested and named arbitrarily, however depending on authorization schemes used the basic container is often named after a group or a user in order to make authorization checks simpler. Getting keys ------------ A GET operation with the name of the key: ``GET /secrets/name/of/key`` A query parameter named 'type' can be provided, in that case the key is returned only if it matches the requested type. Returns: - 200 and a JSON formatted key in case of success. - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 if no key was found - 406 not acceptable, key type unknown/not permitted Storing keys ------------ A PUT operation with the name of the key: ``PUT /secrets/name/of/key`` The Content-Type MUST be 'application/json' The Content-Length MUST be specified, and the body MUST be a key in one of the valid formats described above. Returns: - 201 in case of success - 400 if the request format is invalid - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 one of the elements of the path is not a valid container - 405 if the target is a directory instead of a key (path ends in '/') - 406 not acceptable, key type unknown/not permitted - 409 if the key already exists Deleting keys ------------- A DELETE operation with the name of the key: ``DELETE /secrets/name/of/key`` Returns: - 204 in case of success - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 if no key was found - 406 not acceptable, type unknown/not permitted Listing containers ------------------ A GET operation on a path that ends in a '/' translates into a listing for a container: ``GET /secrets/container/`` Implementations may assume a default container if none is explicitly provided: GET /secrets/ may return only keys under //\* Returns: - 200 in case of success and a dictionary containing a list of all keys in the container and all subcontainers - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 if no key was found - 406 not acceptable, type unknown/not permitted Creating containers ------------------- A POST operation on a path will create a container with that name. A trailing '/' is required: ``POST /secrets/mycontainer/`` Default containers may be automatically created by an implementation. Returns: - 201 in case of success - 400 if the request format is invalid - 401 if authentication is necessary - 403 if access to the key is forbidden - 404 one of the elements of the path is not a valid container - 406 not acceptable, type unknown/not permitted - 409 if the container already exists Deleting containers ------------------- A DELETE operation with the name of the container: ``DELETE /secrets/mycontainer/`` Returns: - 204 in case of success - 401 if authentication is necessary - 403 if access to the container is forbidden - 404 if no container was found - 406 not acceptable, type unknown/not permitted - 409 if the container is not empty custodia-0.5.0/docs/source/commands.rst000066400000000000000000000004161310463436300201160ustar00rootroot00000000000000################# Custodia commands ################# custodia server =============== .. argparse:: :ref: custodia.server.default_argparser :prog: custodia custodia client =============== .. argparse:: :ref: custodia.cli.main_parser :prog: custodia-cli custodia-0.5.0/docs/source/conf.py000066400000000000000000000214521310463436300170650ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Custodia documentation build configuration file, created by # sphinx-quickstart on Wed Apr 15 17:49:46 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import sphinx try: import sphinxcontrib.spelling except ImportError: HAS_SPELLING = False else: HAS_SPELLING = True # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. HERE = os.path.dirname(os.path.abspath(__file__)) SRCDIR = os.path.abspath(os.path.join(HERE, '..', '..', 'src')) sys.path.insert(0, SRCDIR) about = {} with open(os.path.join(SRCDIR, 'custodia', '__about__.py')) as f: exec(f.read(), about) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', # 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', # sphinx-argparse 'sphinxarg.ext', ] if HAS_SPELLING: extensions.append('sphinxcontrib.spelling') # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = about['__title__'] copyright = about['__copyright__'] # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = ".".join(str(v) for v in about['__version_info__'][:2]) # The full version, including alpha/beta/rc tags. release = about['__version__'] # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Custodiadoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Custodia.tex', u'Custodia Documentation', u'Custodia Contributors', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'custodia', u'Custodia Documentation', [u'Custodia Contributors'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Custodia', u'Custodia Documentation', u'Custodia Contributors', 'Custodia', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. # Disabled, see https://github.com/latchset/custodia/issues/13 # intersphinx_mapping = {'http://docs.python.org/': None} custodia-0.5.0/docs/source/config.rst000066400000000000000000000071051310463436300175640ustar00rootroot00000000000000############### Custodia Config ############### Custodia uses a ini-style configuration file with `extended interpolation `_. Sections ======== globals ------- server_url [str] * http://hostname:port * https://hostname:port * http+unix://%2Fpath%2Fto%2Fserver_sock Custodia supports systemd socket activation. The server automatically detects socket activation and uses the first file descriptor (requires python-systemd). Socket family and port/path must match settings in configuration file:: $ /usr/lib/systemd/systemd-activate -l $(pwd)/custodia.sock python -m custodia.server custodia.conf server_socket [str] Path to :const:`AF_UNIX` socket file. In the absence of *server_url* and *server_socket*, the default value for *server_socket* is ``/var/run/custodia/${instance}.sock``. server_string [str] String to send as HTTP Server string debug [bool, default=False] enable debugging makedirs [bool, default=False] Create *libdir*, *logdir*, *rundir*, and *socketdir*. tls_certfile [str] The filename of the server cert file and its intermediate certs. The server cert file can also contain the private key. The option is required for HTTPS server. tls_keyfile [str] The filename of the private key file for Custodia's HTTPS server. tls_cafile [str] Path to a file with trust anchors. The trust anchors are used to verify client certificates. When the option is not set, Python loads root CA from the system's default verify location. tls_verify_client [bool, default=False] Require TLS client certificates authenticators -------------- Example:: [auth:header] handler = custodia.httpd.authenticators.SimpleHeaderAuth name = REMOTE_USER authorizers ----------- Example:: [authz:namespaces] handler = custodia.httpd.authorizers.UserNameSpace path = /secrets/ store = simple stores ------ Example:: [store:simple] handler = custodia.store.sqlite.SqliteStore dburi = /path/to/secrets.db table = secrets consumers --------- Example:: [/] handler = custodia.root.Root store = simple Special sections ================ DEFAULT ------- The :const:`DEFAULT` section contains default values for all sections. Some values are always defined. Predefined values can be overridden. Paths to files and directories are converted to absolute paths. hostname hostname from ``socket.gethostname()`` instance name of the Custodia server instance or empty string configdir Directory of the server's config file confdpattern Glob pattern for additional config files libdir Directory for persistent variable data (e.g. sqlite database) logdir Directory for log files rundir Directory for ephemeral data (e.g. ccache) socketdir Directory for socket file Example for ``custodia --instance=example /etc/custodia/ex.conf`` with an empty config file:: [DEFAULT] hostname = hostname.example configdir = /etc/custodia confdpattern = /etc/custodia/ex.conf.d/*.conf libdir = /var/lib/custodia/example logdir = /var/log/custodia/example rundir = /var/run/custodia/example socketdir = /var/run/custodia [global] auditlog = /var/log/custodia/example/audit.log debug = False server_socket = /var/run/custodia/example.sock makedirs = True umask = 027 ENV --- The :const:`ENV` is populated with all environment variables. To reference :const:`HOME` variable:: server_socket = ${ENV:HOME}/server_socket .. spelling:: Fpath Fto Fserver custodia-0.5.0/docs/source/container.rst000066400000000000000000000065721310463436300203100ustar00rootroot00000000000000################## Custodia Container ################## The Custodia Docker image allows the Custodia server to be easily run in a container. By locating the socket that Custodia listens on in a data volume that is located on the host, other containers and applications on the host itself can use your Custodia container to manage secrets. Data Volumes ============ The following data volumes are defined in the Custodia Docker image: * /etc/custodia * /var/lib/custodia * /var/log/custodia * /var/run/custodia When a new Custodia container is created, new mount points on the native host will be automatically created for each of these volumes. You can use the ``docker inspect`` command to display the location of the volume on the host with the following command:: docker inspect -f '{{ range .Mounts }}{{ printf "%s -> %s\n" .Source .Destination }}{{ end }}' By default, the mount point on the host will use a very long unique name. This causes problems with the Custodia socket file, as a UNIX domain socket path is not allowed to be over 108 bytes in length. The Custodia socket file path will exceed this limit unless you specify a different host mount point when creating your container. This can be seen in the :ref:`example-section` section below. Systems using SELinux will need to use the ``Z`` mount option for the ``/var/run/custodia`` volume to allow proper access to the socket file. .. _example-section: Example ======= The following example creates a Custodia container where Docker will automatically create the local volume mount locations with the exception of ``/var/run/custodia``. This volume will be mounted from ``/var/run/custodia`` on the host to allow other applications to access the Custodia socket file in it's standard location. The Custodia container runs as a ``custodia`` user using the uid number ``447``. To allow the Custodia service in the container to create the socket file on the host, we will create a local ``custodia`` user and group with the expected uid and gid numbers, then use it to create the volume mount point on the host with the proper permissions and ownership. The commands to do this are:: $ sudo groupadd -r custodia -g 447 $ sudo useradd -u 447 -r -g custodia custodia $ sudo mkdir -m 755 /var/run/custodia $ sudo chown custodia /var/run/custodia Now that the volume mount point for the socket file is created on the host, the container can be created using the following command:: $ sudo docker run -it -v /var/run/custodia:/var/run/custodia:Z The Custodia service should start successfully, and its logs will be displayed in the terminal where the container was created. Once the container is created, you can list the location of the mounted volumes:: $ sudo docker inspect -f '{{ range .Mounts }}{{ printf "%s -> %s\n" .Source .Destination }}{{ end }}' /var/run/custodia -> /var/run/custodia /var/lib/docker/volumes/a2eb52bc00586536b70a27b4395a8d4f0bd782290783132f7bdcf2bb16524250/_data -> /var/lib/custodia /var/lib/docker/volumes/88d00edd2c7d6c2da94fa4b8eb97246450e39d108e7fb53cff2d832969482d1c/_data -> /var/log/custodia You can test that your Custodia container is working from your host by running the following command:: $ sudo curl --unix-socket /var/run/custodia/custodia.sock -X GET http://localhost/ {"message": "Quis custodiet ipsos custodes?"} custodia-0.5.0/docs/source/examples/000077500000000000000000000000001310463436300174005ustar00rootroot00000000000000custodia-0.5.0/docs/source/examples/cfgparser.py000066400000000000000000000114641310463436300217340ustar00rootroot00000000000000# Copyright (C) 2016 Custodia Project Contributors - see LICENSE file import collections import json from custodia.client import CustodiaSimpleClient from custodia.compat import configparser from requests.exceptions import HTTPError class CustodiaSectionProxy(configparser.SectionProxy): """A section proxy that supports getsecret() """ def getsecret(self, option, fallback=None, **kwargs): # keyword-only arguments raw = kwargs.get('raw', False) var = kwargs.get('vars', None) return self._parser.getsecret(self._name, option, raw=raw, vars=var, fallback=fallback) class CustodiaMapping(collections.Mapping): """Custodia client proxy The class provides a read-only mapping interface that forwards item lookup to a Custodia client. It is used to implement ${CUSTODIA:some/key} interpolation where CUSTODIA is an instance of this class and 'some/key' is requested from a Custodia server. """ __slots__ = ('_parser', ) def __init__(self, parser): self._parser = parser def __getitem__(self, item): return self._parser.custodia_client.get_secret(item) def __len__(self): # don't bother to get len or iter from remote return 0 def __iter__(self): return {}.__iter__() class CustodiaConfigParser(configparser.ConfigParser): """Python 3 like config parser with Custodia support. Example config:: [custodia_client] url = https://custodia.example/secrets [example] password = test/key [interpolation] password = ${CUSTODIA:test/key} parser = CustodiaConfigParser() secret = parser.getsecret('example', 'password') secret = parser.get('interpolation', 'password') The Custodia client instance can either be passed to CustodiaConfigParser or loaded from the [custodia_client] section. """ _DEFAULT_INTERPOLATION = configparser.ExtendedInterpolation() custodia_client_section = 'custodia_client' custodia_section = 'CUSTODIA' def __init__(self, defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, custodia_client=None, **kwargs): super(CustodiaConfigParser, self).__init__( defaults=defaults, dict_type=dict_type, allow_no_value=allow_no_value, **kwargs) self._sections[self.custodia_section] = CustodiaMapping(self) self._custodia_client = custodia_client def __getitem__(self, key): item = super(CustodiaConfigParser, self).__getitem__(key) # wrap SectionProxy in CustodiaSectionProxy if not isinstance(item, CustodiaSectionProxy): item = CustodiaSectionProxy(item.parser, item.name) self._proxies[key] = item return item @property def custodia_client(self): if self._custodia_client is None: sec = self.custodia_client_section url = self.get(sec, 'url') client = CustodiaSimpleClient(url) headers = self.get(sec, 'headers', fallback=None) if headers: headers = json.loads(headers) client.headers.update(headers) tls_cafile = self.get(sec, 'tls_cafile', fallback=None) if tls_cafile: client.set_ca_cert(tls_cafile) certfile = self.get(sec, 'tls_certfile', fallback=None) keyfile = self.get(sec, 'tls_keyfile', fallback=None) if certfile: client.set_client_cert(certfile, keyfile) self._custodia_client = client return self._custodia_client def getsecret(self, section, option, **kwargs): """Get a secret from Custodia """ # keyword-only arguments, vars and fallback are directly passed through raw = kwargs.get('raw', False) value = self.get(section, option, **kwargs) if raw: return value return self.custodia_client.get_secret(value) def demo(): import textwrap cfg = textwrap.dedent(u""" [custodia_client] url = http+unix://%2E%2Fserver_socket/secrets headers = {"REMOTE_USER": "user"} [example] password = test/key [interpolation] password = ${CUSTODIA:test/key} """) parser = CustodiaConfigParser() parser.read_string(cfg) # create entries try: c = parser.custodia_client.list_container('test') except HTTPError: parser.custodia_client.create_container('test') c = [] if 'key' not in c: parser.custodia_client.set_secret('test/key', 'secret password') # get entries from Custodia secret = parser.getsecret('example', 'password') print(secret) secret = parser.get('interpolation', 'password') print(secret) if __name__ == '__main__': demo() custodia-0.5.0/docs/source/examples/cfgparser.rst000066400000000000000000000001711310463436300221050ustar00rootroot00000000000000configparser extension ====================== :download:`cfgparser.py ` .. literalinclude:: cfgparser.py custodia-0.5.0/docs/source/examples/index.rst000066400000000000000000000001321310463436300212350ustar00rootroot00000000000000Examples ======== .. toctree:: :maxdepth: 2 misc.rst cfgparser.rst yaml.rst custodia-0.5.0/docs/source/examples/misc.rst000066400000000000000000000022011310463436300210600ustar00rootroot00000000000000Clients ======= Docker credential store ----------------------- `docker-credential-custodia`_ is an implementation of `Docker Credentials Store`_ in Go. .. _Docker Credentials Store: http://www.projectatomic.io/blog/2016/03/docker-credentials-store/ .. _docker-credential-custodia: https://github.com/latchset/docker-credential-custodia curl ---- Test Custodia:: $ curl --unix-socket /var/run/custodia/custodia.sock -X GET http://localhost/ {"message": "Quis custodiet ipsos custodes?"} Initialize a container for secrets:: $ curl --unix-socket /var/run/custodia/custodia.sock -X POST http://localhost/secrets/container/ Create or update a secret:: $ curl --unix-socket /var/run/custodia/custodia.sock -H "Content-Type: application/json" -X PUT http://localhost/secrets/container/key -d '{"type": "simple", "value": "secret value"}' Get a secret:: $ curl --unix-socket /var/run/custodia/custodia.sock -X GET http://localhost/secrets/container/key {"type":"simple","value":"secret value"} Delete a secret:: $ curl --unix-socket /var/run/custodia/custodia.sock -X DELETE http://localhost/secrets/container/key custodia-0.5.0/docs/source/examples/yaml.rst000066400000000000000000000001561310463436300210760ustar00rootroot00000000000000PyYAML constructor ================== :download:`yaml_ext.py ` .. literalinclude:: yaml_ext.py custodia-0.5.0/docs/source/examples/yaml_ext.py000066400000000000000000000022121310463436300215710ustar00rootroot00000000000000# Copyright (C) 2016 Custodia Project Contributors - see LICENSE file import yaml from requests.exceptions import HTTPError from custodia.client import CustodiaSimpleClient class CustodiaSimpleConstructor(object): yaml_tag = u'!custodia/simple' def __init__(self, url): self.client = CustodiaSimpleClient(url) def __call__(self, loader, node): value = loader.construct_scalar(node) return self.client.get_secret(value) def demo(): constructor = CustodiaSimpleConstructor( 'http+unix://%2E%2Fserver_socket/secrets' ) constructor.client.headers['REMOTE_USER'] = 'user' # create entries try: c = constructor.client.list_container('test') except HTTPError: constructor.client.create_container('test') c = [] if 'key' not in c: constructor.client.set_secret('test/key', 'secret password') yaml.add_constructor(CustodiaSimpleConstructor.yaml_tag, constructor) yaml_str = 'password: !custodia/simple test/key' print(yaml_str) result = yaml.load(yaml_str) print(result) if __name__ == '__main__': demo() custodia-0.5.0/docs/source/index.rst000066400000000000000000000020541310463436300174240ustar00rootroot00000000000000.. Custodia documentation master file, created by sphinx-quickstart on Wed Apr 15 17:49:46 2015. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Custodia's documentation! ==================================== Custodia is a Secrets Service Provider, it stores or proxies access to keys, password, and secret material in general. Custodia is built to use the HTTP protocol and a RESTful API as an IPC mechanism over a local Unix Socket. It can also be exposed to a network via a Reverse Proxy service assuming proper authentication and header validation is implemented in the Proxy. Custodia is modular, the configuration file controls how authentication, authorization, storage and API plugins are combined and exposed. Contents: .. toctree:: :maxdepth: 2 readme.rst quick.rst config.rst commands.rst api.rst examples/index.rst plugins/index.rst container.rst Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` custodia-0.5.0/docs/source/plugins/000077500000000000000000000000001310463436300172435ustar00rootroot00000000000000custodia-0.5.0/docs/source/plugins/authenticators.rst000066400000000000000000000013561310463436300230370ustar00rootroot00000000000000Authenticators ============== .. autosummary:: :nosignatures: custodia.httpd.authenticators.SimpleCredsAuth custodia.httpd.authenticators.SimpleHeaderAuth custodia.httpd.authenticators.SimpleAuthKeys custodia.httpd.authenticators.SimpleClientCertAuth .. autoclass:: custodia.httpd.authenticators.SimpleCredsAuth :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.httpd.authenticators.SimpleHeaderAuth :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.httpd.authenticators.SimpleAuthKeys :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.httpd.authenticators.SimpleClientCertAuth :members: :undoc-members: :show-inheritance: custodia-0.5.0/docs/source/plugins/authorizers.rst000066400000000000000000000010151310463436300223510ustar00rootroot00000000000000Authorizers =========== .. autosummary:: :nosignatures: custodia.httpd.authorizers.SimplePathAuthz custodia.httpd.authorizers.UserNameSpace custodia.message.kem.KEMKeysStore .. autoclass:: custodia.httpd.authorizers.SimplePathAuthz :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.httpd.authorizers.UserNameSpace :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.message.kem.KEMKeysStore :members: :undoc-members: :show-inheritance: custodia-0.5.0/docs/source/plugins/baseclasses.rst000066400000000000000000000014501310463436300222650ustar00rootroot00000000000000Plugin base classes =================== .. autosummary:: :nosignatures: custodia.plugin.CustodiaPlugin custodia.plugin.HTTPAuthenticator custodia.plugin.HTTPAuthorizer custodia.plugin.CSStore custodia.plugin.HTTPConsumer custodia.plugin.PluginOption .. autoclass:: custodia.plugin.CustodiaPlugin :members: :undoc-members: .. autoclass:: custodia.plugin.HTTPAuthenticator :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.plugin.HTTPAuthorizer :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.plugin.CSStore :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.plugin.HTTPConsumer :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.plugin.PluginOptioncustodia-0.5.0/docs/source/plugins/clients.rst000066400000000000000000000007551310463436300214450ustar00rootroot00000000000000Clients ======= .. autosummary:: :nosignatures: custodia.client.CustodiaHTTPClient custodia.client.CustodiaSimpleClient custodia.client.CustodiaKEMClient .. autoclass:: custodia.client.CustodiaHTTPClient :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.client.CustodiaSimpleClient :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.client.CustodiaKEMClient :members: :undoc-members: :show-inheritance: custodia-0.5.0/docs/source/plugins/consumers.rst000066400000000000000000000006571310463436300220230ustar00rootroot00000000000000Consumers ========= .. autosummary:: :nosignatures: custodia.secrets.Secrets custodia.forwarder.Forwarder custodia.root.Root .. autoclass:: custodia.secrets.Secrets :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.forwarder.Forwarder :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.root.Root :members: :undoc-members: :show-inheritance: custodia-0.5.0/docs/source/plugins/index.rst000066400000000000000000000043021310463436300211030ustar00rootroot00000000000000Custodia Plugins ================ Custodia is built as an HTTP based pipeline where each stage of the process is pluggable. The main stages are: * Authentication * Authorization * Request handling * Storage Plugin Stages ------------- Authentication ^^^^^^^^^^^^^^ Authentication is handled by a stackable set of arbitrary plugins (python modules referenced in the configuration file). If any of the authentication plugins returns a negative answer the request is aborted with a 403 error. If any returns a positive answer then the request is allowed to proceed to the next phase. If none of the plugins returns either a positive or negative answer the request fails, as by default access is denied. Authorization ^^^^^^^^^^^^^ Authorization is also handled by a stackable set of plugins, however in this case plugins are ordered. As soon as one plugin returns a positive or negative answer the request can pass to the next stage or is refused. If no plugin returns a positive or negative answer, the request is refused as access is denied by default. Request Handling ^^^^^^^^^^^^^^^^ Request handling is also pluggable and depends mostly on the path used in the request. Multiple handlers can be used, and each will be associated to a path. Handlers can be arbitrarily complex, custodia provides a default handler called 'secrets', this handler can manage access to secrets using various request message types (currently simple or key-exchange-message). Storage ^^^^^^^ The storage in custodia is also pluggable and doesn't need to be an actual database or file system. It can as well be a chaining module that will call another Custodia instance up the chain, usually massaging the request path and the request headers to provide hints or authentication tokens to the upstream Custodia instance. This is very powerful and allows the infrastructure to partition the namespace and redirect requests to multiple sources, based on arbitrary rules, either for load balancing reasons, or in order to segregate different tenants to different storage systems. Plugin Modules -------------- .. toctree:: :maxdepth: 2 baseclasses.rst authenticators.rst authorizers.rst consumers.rst stores.rst clients.rst custodia-0.5.0/docs/source/plugins/stores.rst000066400000000000000000000007571310463436300213250ustar00rootroot00000000000000Stores ====== .. autosummary:: :nosignatures: custodia.store.sqlite.SqliteStore custodia.store.etcdstore.EtcdStore custodia.store.encgen.EncryptedOverlay .. autoclass:: custodia.store.sqlite.SqliteStore :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.store.etcdstore.EtcdStore :members: :undoc-members: :show-inheritance: .. autoclass:: custodia.store.encgen.EncryptedOverlay :members: :undoc-members: :show-inheritance: custodia-0.5.0/docs/source/quick.rst000066400000000000000000000224051310463436300174330ustar00rootroot00000000000000########### Quick Start ########### This is a quick start guide to get something up quickly to see the API in action. Installing ========== We'll simply clone the git tree and use Custodia in place to quickly test it. Clone the repository, and run the make egg_info command to prepare the tree for execution:: $ git clone https://github.com/latchset/custodia.git $ cd custodia $ make egg_info Configuring =========== We'll use a simple a bare minimum configuration to start off. Write a file named quick.conf with the following contents (feel free to omit the comments):: [global] # Listen on a socket named './quick' server_socket = ./quick # Accepts any request that specifies an arbitrary REMOTE_USER header [auth:header] handler = SimpleHeaderAuth header = REMOTE_USER # Allow requests for all paths under '/' and '/secrets/' [authz:paths] handler = SimplePathAuthz paths = / /secrets/ # Store secrets in a sqlite database called quick.db in the table 'secrets' [store:quick] handler = SqliteStore dburi = quick.db table = secrets # Serve starting from '/' and using the 'quick' store and the 'Root' handler [/] handler = Root store = quick Running ======= Now all we need is to start the server. We do that with the following command:: $ python -m custodia.server quick.conf The server will output to the terminal logs about the operations being performed against it. Testing ======= Once the server is started we can move to another terminal to test it. To avoid some typing we'll create a shell alias:: $ alias curls='curl -s --unix-socket ./quick -H "REMOTE_USER: me"' Let's use curl to fetch the root object :: $ curls http://localhost/ {"message": "Quis custodiet ipsos custodes?"} The message "Quis custodiet ipsos custodes?" is emitted by the Root handler by default when querying the root ('/'). It is used to test that the basic pipeline is working and authorizing correctly. The Root handler automatically adds also a 'secrets' handler under the path '/secrets/', this is the actual basename of our secrets storage and will always be used going forward. Let's now create a new container for our secrets :: $ curls -X POST http://localhost/secrets/bucket/ Be sure to always pass the trailing '/' character, or the server will assume you are trying to operate on a key rather than a container and will return you an error. Now that we have a container let's store a secret in the simplest way :: $ curls -H "Content-Type: application/octet-stream" -X PUT http://localhost/secrets/bucket/mykey -d 'P@ssw0rd' This command is telling the server that we want to store raw data (by passing the "Content-Type: application/octet-stream" header) in the secret named "mykey" in the container named "bucket". The content is the string "P@ssw0rd". NOTE: you must provide a Content-Type header or the operation will fail, the supported types are: application/json and application/octet-stream Let's now retrieve the secret we just stored :: $ curls -H "Accept: application/octet-stream" http://localhost/secrets/bucket/mykey P@ssw0rd NOTE: when getting the header to use to indicate the Content-Type we want is "Accept: application/octet-stream", this follows the standard HTTP protocol. When the raw data method is used, the database will generally store data base64 encoded, let's try to get the same data without specifying an accepted content type (which is the same as specifying "Accept: application/json") :: $ curls http://localhost/secrets/bucket/mykey {"type":"simple","value":"UEBzc3cwcmQ="} NOTE: The value is the base64 encoding of the string "P@ssw0rd" Let's now try to list the contents of our container :: $ curls http://localhost/secrets/bucket/ ["mykey"] We are returned a json array with the list of available keys. Let's now remove this key :: $ curls -X DELETE http://localhost/secrets/bucket/mykey And list again our container :: $ curls http://localhost/secrets/bucket/ [] Finally let's cleanup and remove the container too :: $ curls -X DELETE http://localhost/secrets/bucket/ Adding Authentication ===================== You may notice that we are currently performing no real authentication, we are just advising the server to treat us as the "me" user. This phony authentication is actually used when setting up Custodia behind a real HTTP server like Apache Httpd or Nginx and using one of their modules for authentication. For simpler setups where custodia is directly accessed we can use one of the available modules for actual authentication. We can add a new authentication module to the configuration. In quick.conf add :: [auth:sak] handler = custodia.httpd.authenticators.SimpleAuthKeys store_namespace = keys/sak store = quick We chose the namespace keys/sak as this will allow us to manipulate keys via normal methods by placing them under the container named 'sak'. Restart the server and run the following operations :: $ curls -X POST http://localhost/secrets/sak/ $ curls -H "Content-Type: application/json" -X PUT http://localhost/secrets/sak/qid -d '{"type":"simple","value":"secretcode"}' We can now created a new key called qid (from the unimaginative Quick ID) and we can now authenticate with our new "user" QID and the proper secret key. Set a new alias :: $ alias curlq='curl -s --unix-socket ./quick -H "CUSTODIA_AUTH_ID: qid" -H "CUSTODIA_AUTH_KEY: secretcode"' Now remove the section named '[auth:header]' from the quick.conf configuration file and restart the server. Try to get keys with the old alias:: $ curls http://localhost/ You will get a 403 error. However the new alias with the correct authentication keys will work. Try to get keys with the new alias:: $ curlq http://localhost/ Adding Authorization ==================== Now that we can have authentication using proper keys it's time to deal with authorization. In most cases we want to restrict access by user. When using the SimpleAuthKeys authentication method Custodia will treat the CUSTODIA_AUTH_ID string as the user name string (equivalent to using the REMOTE_USER header with the SimpleHeaderAuth authentication method). We can restrict access by user using the UserNameSpace handler. Remove the current [authz:paths] section and replace it with:: [authz:namespaces] handler = UserNameSpace path = /secrets/ store = quick Restart the server and try to fetch the base path. It will fail:: $ curlq http://localhost/ It fails because we change authorization and we do not allow '/' anymore, only paths under /secrets/ are now allowed. However if you try to fetch any random path under /secrets that will also fail! This is because the UserNameSpace handler allows to access only containers under the specified path that are named exactly as the authenticating user. So try this:: $ curlq -X POST http://localhost/secrets/qid/ It will create a new container for our user "qid", now we are allowed to create and fetch any key under /secrets/qid/ Adding Encryption ================= So far we have been using the most basic database used for testing which is sqlite based. If you use the sqlite3 command to look into the secrets table you will pretty quickly realize that all the stored secrets are available in plain text. Custodia comes with a nice overlay database type that can encrypt the data stored in any backend storage. It is useful in case the backend chosen does not encrypt data at rest on its own. We'll also show how we can add a whole new subtree backed by this new database so we can keep using both in parallel Let's add a new database with overlay encryption to the configuration file:: [store:overlayed] handler = SqliteStore dburi = quick.db table = encrypted [store:encrypted] handler = EncryptedOverlay backing_store = overlayed master_key = quick.key master_enctype = A128CBC-HS256 [authz:encrypted] handler = UserNameSpace path = /encrypted/ store = encrypted [/encrypted] handler = Secrets store = encrypted We will also need to create a key file with the master key. The contents of the file are a symmetric key formatted according to the JWK_ specification. For testing we'll do this:: $ echo '{"kty":"oct","k":"tnUJ1XMLOXJ7y95SWmEeq514-YSbVQVo1Hc8eLdxkTE"}' > quick.key Restart the server and now try to create a container for qid under the /encrypted tree and then try to store a secret there :: $ curlq -X POST http://localhost/encrypted/qid/ $ curlq -H "Content-Type: application/octet-stream" -X PUT http://localhost/encrypted/qid/mykey -d 'P@ssw0rd' If we now examine the database with the sqlite3 editor we'll see that the keys in the 'encrypted' table are indeed encrypted (the encryption format is just a JWE_ token). We can also see that the key names are not encrypted. This overlay only encrypts the individual keys, not the metadata surrounding them. Closing ======= In this Quick Start Guide you've seen how to create and fetch secrets with the Custodia API and a few of the simple authentication and authorization plugins available. Other plugins are available, and custom ones are rather simple to build. Have Fun! .. _JWK: https://tools.ietf.org/html/rfc7517 .. _JWE: https://tools.ietf.org/html/rfc7516 .. spelling:: Quis custodiet ipsos custodes qid mykey custodia-0.5.0/docs/source/readme.rst000066400000000000000000000024341310463436300175540ustar00rootroot00000000000000.. WARNING: AUTO-GENERATED FILE. DO NOT EDIT. Custodia ======== A tool for managing secrets. See our `Quick Start Guide `__ Custodia is a project that aims to define an API for modern cloud applications that allows to easily store and share passwords, tokens, certificates and any other secret in a way that keeps data secure, manageable and auditable. The Custodia project offers example implementations of clear text and encrypted backends, and aims to soon provide drivers to store data in external data stores like the Vault Project, OpenStack's Barbican, FreeIPA's Vault and similar. In future the Custodia project plans to enhance and enrich the API to provide access to even more secure means of dealing with private keys, like HSM as a Service and other similar security systems. See the Custodia documentation for more information: https://custodia.readthedocs.io Requirements ------------ Runtime ~~~~~~~ - configparser (Python 2.7) - cryptography - jwcrypto >= 0.2 - requests - six Installation and testing ~~~~~~~~~~~~~~~~~~~~~~~~ - pip - setuptools >= 18.0 - tox >= 2.3.1 - wheel API stability ------------- Some APIs are provisional and may change in the future. - Command line interface in module ``custodia.cli``. - The script custodia-cli. custodia-0.5.0/docs/source/spelling_wordlist.txt000066400000000000000000000010331310463436300220640ustar00rootroot00000000000000api Args auditable auth authenticator authenticators Authenticators authorizer authorizers Authorizers authz autogen backend backends Barbican basename boolean cafile ccache certfile cfgparser cli conf confdpattern config configdir custodia Custodia decrypt del enctype filename gid hostname http Httpd Indices ini jku json kem keyfile libdir logdir makedirs metadata mkdir namespace Nginx pluggable plugin Plugin plugins rmdir rundir runtime sak socketdir sqlite stackable subcontainers subtree systemd timestamp tls TLS tox uid unix url custodia-0.5.0/examples/000077500000000000000000000000001310463436300151505ustar00rootroot00000000000000custodia-0.5.0/examples/client_enc.key000066400000000000000000000064241310463436300177730ustar00rootroot00000000000000[{"p":"2rnSOV4hKSN8sS4CgcQHFbs08XboFDqKum3sc4h3GRxrTmQdl1ZK9uw-PIHfQP0FkxXVrx-WE-ZEbrqivH_2iCLUS7wAl6XvARt1KkIaUxPPSYB9yk31s0Q8UK96E3_OrADAYtAJs-M3JxCLfNgqh56HDnETTQhH3rCT5T3yJws","kid":"984f6264-ce8e-407b-9e44-f9c4aaee3f71","dq":"AvfS0-gRxvn0bwJoMSnFxYcK1WnuEjQFluMGfwGitQBWtfZ1Er7t1xDkbN9GQTB9yqpDoYaN06H7CFtrkxhJIBQaj6nkF5KKS3TQtQ5qCzkOkmxIe3KRbBymXxkb5qwUpX5ELD5xFc6FeiafWYY63TmmEAu_lRFCOJ3xDea-ots","qi":"lSQi-w9CpyUReMErP1RsBLk7wNtOvs5EQpPqmuMvqW57NBUczScEoPwmUqqabu9V0-Py4dQ57_bapoKRu1R90bvuFnU63SHWEFglZQvJDMeAvmj4sm-Fp0oYu_neotgQ0hzbI5gry7ajdYy9-2lNx_76aBZoOUu9HCJ-UsfSOI8","q":"1u_RiFDP7LBYh3N4GXLT9OpSKYP0uQZyiaZwBtOCBNJgQxaj10RWjsZu0c6Iedis4S7B_coSKB0Kj9PaPaBzg-IySRvvcQuPamQu66riMhjVtG6TlV8CLCYKrYl52ziqK0E_ym2QnkwsUX7eYTB7LbAHRK9GqocDE5B0f808I4s","e":"AQAB","dp":"KkMTWqBUefVwZ2_Dbj1pPQqyHSHjj90L5x_MOzqYAJMcLMZtbUtwKqvVDq3tbEo3ZIcohbDtt6SbfmWzggabpQxNxuBpoOOf_a_HgMXK_lhqigI4y_kqS1wY52IwjUn5rgRrJ-yYo1h41KR-vz2pYhEAeYrhttWtxVqLCRViD6c","n":"t6Q8PWSi1dkJj9hTP8hNYFlvadM7DflW9mWepOJhJ66w7nyoK1gPNqFMSQRyO125Gp-TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR0-Iqom-QFcNP8Sjg086MwoqQU_LYywlAGZ21WSdS_PERyGFiNnj3QQlO8Yns5jCtLCRwLHL0Pb1fEv45AuRIuUfVcPySBWYnDyGxvjYGDSM-AqWS9zIQ2ZilgT-GqUmipg0XOC0Cc20rgLe2ymLHjpHciCKVAbY5-L32-lSeZO-Os6U15_aXrk9Gw8cPUaX1_I8sLGuSiVdt3C_Fn2PZ3Z8i744FPFGGcG1qs2Wz-Q","d":"GRtbIQmhOZtyszfgKdg4u_N-R_mZGU_9k7JQ_jn1DnfTuMdSNprTeaSTyWfSNkuaAwnOEbIQVy1IQbWVV25NY3ybc_IhUJtfri7bAXYEReWaCl3hdlPKXy9UvqPYGR0kIXTQRqns-dVJ7jahlI7LyckrpTmrM8dWBo4_PMaenNnPiQgO0xnuToxutRZJfJvG4Ox4ka3GORQd9CsCZ2vsUDmsXOfUENOyMqADC6p1M3h33tsurY15k9qMSpG9OX_IJAXmxzAh_tWiZOwk2K4yxH9tS3Lq1yX8C1EWmeRDkK2ahecG85-oLKQt5VEpWHKmjOi_gJSdSgqcN96X52esAQ","kty":"RSA","use":"sig"},{"p":"2rnSOV4hKSN8sS4CgcQHFbs08XboFDqKum3sc4h3GRxrTmQdl1ZK9uw-PIHfQP0FkxXVrx-WE-ZEbrqivH_2iCLUS7wAl6XvARt1KkIaUxPPSYB9yk31s0Q8UK96E3_OrADAYtAJs-M3JxCLfNgqh56HDnETTQhH3rCT5T3yJws","kid":"984f6264-ce8e-407b-9e44-f9c4aaee3f71","dq":"AvfS0-gRxvn0bwJoMSnFxYcK1WnuEjQFluMGfwGitQBWtfZ1Er7t1xDkbN9GQTB9yqpDoYaN06H7CFtrkxhJIBQaj6nkF5KKS3TQtQ5qCzkOkmxIe3KRbBymXxkb5qwUpX5ELD5xFc6FeiafWYY63TmmEAu_lRFCOJ3xDea-ots","qi":"lSQi-w9CpyUReMErP1RsBLk7wNtOvs5EQpPqmuMvqW57NBUczScEoPwmUqqabu9V0-Py4dQ57_bapoKRu1R90bvuFnU63SHWEFglZQvJDMeAvmj4sm-Fp0oYu_neotgQ0hzbI5gry7ajdYy9-2lNx_76aBZoOUu9HCJ-UsfSOI8","q":"1u_RiFDP7LBYh3N4GXLT9OpSKYP0uQZyiaZwBtOCBNJgQxaj10RWjsZu0c6Iedis4S7B_coSKB0Kj9PaPaBzg-IySRvvcQuPamQu66riMhjVtG6TlV8CLCYKrYl52ziqK0E_ym2QnkwsUX7eYTB7LbAHRK9GqocDE5B0f808I4s","e":"AQAB","dp":"KkMTWqBUefVwZ2_Dbj1pPQqyHSHjj90L5x_MOzqYAJMcLMZtbUtwKqvVDq3tbEo3ZIcohbDtt6SbfmWzggabpQxNxuBpoOOf_a_HgMXK_lhqigI4y_kqS1wY52IwjUn5rgRrJ-yYo1h41KR-vz2pYhEAeYrhttWtxVqLCRViD6c","n":"t6Q8PWSi1dkJj9hTP8hNYFlvadM7DflW9mWepOJhJ66w7nyoK1gPNqFMSQRyO125Gp-TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR0-Iqom-QFcNP8Sjg086MwoqQU_LYywlAGZ21WSdS_PERyGFiNnj3QQlO8Yns5jCtLCRwLHL0Pb1fEv45AuRIuUfVcPySBWYnDyGxvjYGDSM-AqWS9zIQ2ZilgT-GqUmipg0XOC0Cc20rgLe2ymLHjpHciCKVAbY5-L32-lSeZO-Os6U15_aXrk9Gw8cPUaX1_I8sLGuSiVdt3C_Fn2PZ3Z8i744FPFGGcG1qs2Wz-Q","d":"GRtbIQmhOZtyszfgKdg4u_N-R_mZGU_9k7JQ_jn1DnfTuMdSNprTeaSTyWfSNkuaAwnOEbIQVy1IQbWVV25NY3ybc_IhUJtfri7bAXYEReWaCl3hdlPKXy9UvqPYGR0kIXTQRqns-dVJ7jahlI7LyckrpTmrM8dWBo4_PMaenNnPiQgO0xnuToxutRZJfJvG4Ox4ka3GORQd9CsCZ2vsUDmsXOfUENOyMqADC6p1M3h33tsurY15k9qMSpG9OX_IJAXmxzAh_tWiZOwk2K4yxH9tS3Lq1yX8C1EWmeRDkK2ahecG85-oLKQt5VEpWHKmjOi_gJSdSgqcN96X52esAQ","kty":"RSA","use":"enc"}] custodia-0.5.0/examples/enclite.db000066400000000000000000000220001310463436300170740ustar00rootroot00000000000000SQLite format 3@  -æ ü}}ÍNutableencliteencliteCREATE TABLE enclite (key PRIMARY KEY UNIQUE, value)-Aindexsqlite_autoindex_enclite_1enclite Z·næZ -wcustodiaSAK/testeyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..Xl6QBusQu6TypNndZUDXgw.fMUsxgu3KiyNPAP_---2sg.67V6vbtNUxrVfmIR6UcTag%wcustodiaSAK/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..Hr7nIataVR6tz8a9cOeOIQ.HNg85C-iKEuwshoCAFQ4bQ.r_GedfR67i8zQWQHKOuXFA’:e¤!kemkeys/984f6264-ce8e-407b-9e44-f9c4aaee3f71eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..1GBqPTDUmic6ehA9yFIudQ.k28fkfAow3hzZR2sasV0OK2L6kBPGL-Yxha0VKF0yK2OVUI8wE_30mk1i0ZGqvnGD3Zqp3uwZvxeSxVAqaTwY2sv7oVTahYhzmCAf_3TjYPcbLnct3g5T9hVlLJ2gRPsG6AtX2HjxTRMMFTLeIhx4hfzVOmtvrQYtHmWvKUywi58bARtO8Z6jPxTdaydJFPdqeQDTjZL7W’:e¤!kemkeys/65d64463-7448-499e-8acc-55db2ce67039eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..TgTCdc9h1nkW5x2oKMqw2A.RGAdT0H-WITLZCg9SgQdFXYUHOF6YLmo76sbmVMyVohIc5CzsDwGkMEI-31lw6kKFdjS1RfQ7US0-QpKGOoHNvwjomI0n5komT3tlCfYYP2soZ8zHwKC1tUMWnLBKDanMRHmwTVOwwBvQ0cQC0i-X5S9RpCxUX9Q022R87inScXLYHoVr7uKyRbg7T5RNisCN2EWqxjtYL bQQŠÐŸŸz%custodiaSAK/(-custodiaSAK/test0ekemkeys/984f6264-ce8e-407b-9e44-f9c4aaee3f71/e kemkeys/65d64463-7448-499e-8acc-55db2ce670394NRA8OxkznKwXlnt7I_Lcx7WXaedgb8xd9fPOYUBVeJcUZIwJOoIOzIVQOH6uFe2_GWlRBLqSmWOpYx8mXAnKPlbVR9NQAEa3v1IYtpgKhGai3wFlUp8r2_db6pgemVQJA31qctcs_LROEjA6y91N1vTMP7PEASN9QSzSKHR4wBoYnZGf3Vc2QiDkCZ76wa44CTY4ssTbgso5stv_H5-IZAZBYE7JcdFndVj0zYT70qWPaBjgdK8jRujR_BxXzUcboGRTHiTFd_55_CTPlNtWKFz5JeHIROh_xzwPueYH2okiuZjjfJaQA3ppd63pEL9fFJZAUO-4N1ZYStYdBmAHTbwy0bk-LFNvtf0UfwaKsGbsTdlUkvRrp3hfgrh2BFwIm5XDMpvgvQW_M4O0GXG5VozgDB9DusDG_HRU1elUP88sKaJizjJ9wG7LosLN9ikH8NlYoIpvK5rsJLCtvqVRFQ5KpwlgzYdHj8A87nvSPRo1x6YkTkdCXDPmz0BtATIJT6fdbBJeJj5p2Y6PHWPv3XlXhexq0xt9M4anDFp5VmtgVcnfqb7zQSNICj57jLf-f7yJVEwZ_u2knDm122lItN6pvyppw6K0xFRt1CBrr8JB49fnAXqleTD26ftuth0Ug-RHzV0ypZRCDSeJgGZLy6E31CMXyJ9yLTiDYFKPEyF21yh096-ep5dpCunfIbx-N-0NLwGymV-wDGlkfS0m24ydFcF3rVrT2EIM8L_oT-BmpDNvg4zv50e1RpNB261B_2dBUtHpa_lflA3u6X9viVB4nb63HiF833Wz8PpDbRN7qZCCFtgde4aaV_HH3Z-fTl82x60clj8FO7XeixZmChTPRtOxvreEFEbPYLJiUEaH-jEevHfJEwSTrZPKpWGMHZ073j_-NkUROXkTR99PlU0lDMWcNEeof0HK2JKfTjzked6UUQvA1_JZuhRLjNSHiLPXiysChF4im35j9RGb3C9_wANwBA8Q5UV2c6-CTF9vfmIxdED20Xdxpd_6p08kLt7ZNZDp2-mZnHDZyC5aYjNIG7iPXgtMB4gK-iydRnQNRUabg0n6k-3VLJZuy45FywXYG6M3NDuoFeZSRDd3BHX36BJxL1OzN9bQAfgcRlUcbiZw6nqI5i-sNzWLLDgXcj2aYakqIGZPGlhE6-pEl_Cf_Hu4mMV8XB4c5irOP2KfJ_zcntnOzwuCZHM0QifjgbA64xIj86fz58FubJNjmGZE1CiD9mw472OCX5eHnh2vvR6rINs6PqpkvuVZwudGDT3UfRpLug8jzeZ6X_EdTUVTyvVx3fcItZjxUxT4hKkl1t4ucg3iBjq-nccjZF4efAsN8Qw5LLFPl2BrZphSxO93an2s8g1rRWvmylo6UOy6J0rPKHJQyBP-f9yEkwDhg0P6CSej0CS_wuy-2-zOAlFddtFxic1BR7TV7_OzAJr4sKcjNvqb9o1ebNvnoBWsLw8NhWrrybqzZlhDZm__XYgX9YlaYbVo21ab1OuZqVC8knzC1fcPjjBXbRrgzDWQK5ydKveoGTwUJpTka5IOQAI6F2IdKeUMjbpmjYgT0Gz7zJro32UkhRX63LpJfULpbADmlg4idv6OVsECZ669CxhR1J-TDm1FP3ThG4LhL6eQrZ6TATWEhwLiziBMnG2kMI8TSufVAC9_lwb5__hNknjHt1GBj_N06OppsaoTDzi8J_vs9zjSqx6FFut1-hdQiEtkOG6YfOSXkbhxNhCjLNqKAf_9po4HpJnWqie8Zw24ZAGjGJ6K2FBvDMJOm_2uGAGQ9VwCpBXJsdBnZEsV_LUdQXgXXW_qq49Okrt0I6oi7DKfUBXKjFE_iOETcOT3ZwyCrirpYAs_6ZHKzDnyd01gT39NM8AXnG_7UkDvec0NuCc3Hbzv8So6e5HszBEO0HiRH9J_vKwxbD0h_yrH_6gVo5A2fEIfJIuw7-pffqcmAjMZAbn2nXPufcpDS8wtciRqkoFm-TOaLFqU0xlnFmm43a3v5GIM.OaWFxZQTj8cdwhBx8whoJwUEkZC0R4zTWfzANaQcmz9HJrRSdHkd5A3kkYpcIGpa-yJZ6AAw4lW-aGEA_IhR_UXF3hbH7NyVsHADsMW7ejbIFW2hCrLFhMNpojrxysdDZkNi2X03oLdR9XLUmnQqbhS5zz0uSxyfl1T7va8wD3u7X-KAZmMEK1uZVsdwNzzfLNiviWQSFJ5bW5AjAIdHTUNqI4AHBR85TllkDFlyXTnK2kTEo4TEJemO37h2orbxldbivblucnQbRGSKmWEhmXXu8yr7icOFXV6hGCOjGyhBHdmtn2ut6HEhFX-iPgEDN9xNK3U-ugn4rrcFxt_EEbeuOEi5ILXSJxGaX-O0Q4LzF1-rZHKo7oNvznQzNQtHdMuqusjjhtiThOr0laK5TtkMC6f4S8JUznf62CpTqmjYEnvlzumj32YUWZG2y_MzgvDEF9FotHhtLTVtNYgO2NqdfByJFsqnIxuEkDea19cGamGb2lhXFh-MRBa-oB10xZT-7uZHF-FdPZGskkCHVR-_Inp3jeYgQeQKtg9-21HqcRVFiFrTBoZ0tYjzapuHzeWyTzEWTtOCB1Yrk3xmEM6o7KYwY628sEaQYuShlBh6hqNlSP9v_jU8j5LcgIMNMzCkj24GxZxfaKBI9cAw_7x5VDXLx6suooP5uy_TFJVBlkOzQTX-qAvIGB3Nbsf0vSPq54VqMPbR1wStEAfDKcZ3aFn1TQtYRBCcXjRcUA_69_oFHJ_m1M6LMDzoiGrGHoQwBovV1yooLbyZZFoXkCIyzN7BbvJi-nKBL5ApfNCavAwkBu77MPXciEVWIg7mU227OHske3p83q845iW7YDnds5qUZv2I4pvzep7S7PMPf5NNGe8PwVkWwqXc0Z0u23JIzONUpKGOwU4X5ZczphiB38RKLd2vyMzO_NXmL2WhiJ5OrUAooPQWDnDLVJ23kDuNUP7zoIDB2KJ1oS6HGL5oIbHQKvWz5dvNzn2C8bo9V20ek86FcGhvMEtW5cadIZF4NRZrH5kMZJRk0Jp3rCaxCBnj7-7Wvy-5cIu4S3cFsdKWzr6MuZf4PyQkDRudajL0FpoUklr3NIAEjv6dIIip-3ISP7Rl9cRnep-Nt73HA4NzzPtMxeU35P0zwrRJwmmnto9ksSvMyYfWistzb1SXRzgF8rfwZJ_tkpSF2FGSh8k9YuhGEFQjmEe5ZbcpBvSLBddj82fNNuNmsLX3sn04zri_THNTcQaiacDeEIymzte9Mivm6wy2_9XxT-CY3WXifqNOUN2aIOrlqD16imsz2Z9JrOOXGbsprOHoKO65JGyZ8XQQfRLpfbkkXaO_bqQuRzpuSxqzEHcHk1TdPn-JAp_x_mzjOyVsl1eK66OZTkIfKj7G7aELvJ7DeSlAy5oyFLsGW-aQ0kHi1vpfZdcI2aWzCaVC8RWM114yKyD1V5AmIpXdb6c09JgeHoBEzOIMgZaFJkXJkLIXr1f1b10uBHu-RljmwP1L_uMHvuyWK1Tua5wNEwoujGhor-lZCIl7LJ32iI2iaV-yQAtd_AUl7FYqMCvd2FGSruOmxFFfU3kaHsoxrPGiZhI_9lKSk_A0goFUqbZXv015I0MmRcTti4X8CteknIgsRkNw7-u9PX4T4_fnqDmJfFrKyLYOh32OzpS08G2U20idhGZz56tKvCKjgG5NYIv6ljXwcK546aY8MsDuJwHPlH1kGdz-HRD0v7kN25MNByVNipjNjReCJY0DcQyx5FhZeNGacBYQihxn3j5vZ2l250CdeLMuHVgm8bHYm5Zbvw6mgWrhVPmss3P51GYRuVziqXDXmBgFuIUGisErlP1Q1iHF9E47foukes2TLT85ytMYx4aCu0opZrPNZ4kZklMsebZMZ6BkJ2zr50zQ5bd7cYVq3zL_m-THtwh1ewRoMcRSlqEAMXfqX_QVX48a0YUmXQmGDc7X9QCR9dLHF6akpInICMSgF8hMDDLTZQDWt__ldTlqIGerHd_xSky8IEGbPCqi-PH1e3pQuPM_LFg.38phOAplwSKdfY_9xyKQeA custodia-0.5.0/examples/enclite.sample.key000066400000000000000000000001001310463436300205540ustar00rootroot00000000000000{"kty":"oct","k":"tnUJ1XMLOXJ7y95SWmEeq514-YSbVQVo1Hc8eLdxkTE"} custodia-0.5.0/man/000077500000000000000000000000001310463436300141055ustar00rootroot00000000000000custodia-0.5.0/man/custodia.7000066400000000000000000000007321310463436300160120ustar00rootroot00000000000000.TH "custodia" "7" "2015" "Custodia" "Custodia Secrets Manager" .SH "NAME" custodia .SH "DESCRIPTION" Custodia is a modular and pluggable Secrets Manager. It allows to serve retrieve, manage and store secrets for other applications. It is useful for distributed, stateless applications that use an image file base approach for instantiation like container based images. But it is also useful to manage distribution of key material across a multiple machines over a network. custodia-0.5.0/setup.cfg000066400000000000000000000003651310463436300151570ustar00rootroot00000000000000[bdist_wheel] universal = 1 [aliases] # requires setuptools and wheel package # dnf install python3-setuptools python3-wheel packages = clean --all egg_info bdist_wheel sdist --format=zip sdist --format=gztar release = packages register upload custodia-0.5.0/setup.py000077500000000000000000000100101310463436300150370ustar00rootroot00000000000000#!/usr/bin/python # # Copyright (C) 2015 Custodia project Contributors, for licensee see COPYING from __future__ import print_function import os import sys import setuptools from setuptools import Command, setup SETUPTOOLS_VERSION = tuple(int(v) for v in setuptools.__version__.split(".")) class Version(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): print(self.distribution.metadata.version) about = {} with open(os.path.join('src', 'custodia', '__about__.py')) as f: exec(f.read(), about) requirements = [ 'cryptography', 'jwcrypto', 'six', 'requests' ] # extra requirements etcd_requires = ['python-etcd'] # test requirements test_requires = ['coverage', 'pytest'] + etcd_requires extras_require = { 'etcd_store': etcd_requires, 'test': test_requires, 'test_docs': ['docutils', 'markdown', 'sphinx-argparse', 'sphinxcontrib-spelling'] + etcd_requires, 'test_pep8': ['flake8', 'flake8-import-order', 'pep8-naming'], 'test_pylint': ['pylint'] + test_requires, } # backwards compatibility with old setuptools # extended interpolation is provided by stdlib in Python 3.4+ if SETUPTOOLS_VERSION < (18, 0, 0) and sys.version_info < (3, 4): requirements.append('configparser') else: extras_require[':python_version<"3.4"'] = ['configparser'] with open('README') as f: long_description = f.read() # Plugins custodia_authenticators = [ 'SimpleCredsAuth = custodia.httpd.authenticators:SimpleCredsAuth', 'SimpleHeaderAuth = custodia.httpd.authenticators:SimpleHeaderAuth', 'SimpleAuthKeys = custodia.httpd.authenticators:SimpleAuthKeys', ('SimpleClientCertAuth = ' 'custodia.httpd.authenticators:SimpleClientCertAuth'), ] custodia_authorizers = [ 'SimplePathAuthz = custodia.httpd.authorizers:SimplePathAuthz', 'UserNameSpace = custodia.httpd.authorizers:UserNameSpace', 'KEMKeysStore = custodia.message.kem:KEMKeysStore', ] custodia_clients = [ 'KEMClient = custodia.client:CustodiaKEMClient', 'SimpleClient = custodia.client:CustodiaSimpleClient', ] custodia_consumers = [ 'Forwarder = custodia.forwarder:Forwarder', 'Secrets = custodia.secrets:Secrets', 'Root = custodia.root:Root', ] custodia_stores = [ 'EncryptedOverlay = custodia.store.encgen:EncryptedOverlay', 'EncryptedStore = custodia.store.enclite:EncryptedStore', 'EtcdStore = custodia.store.etcdstore:EtcdStore', 'SqliteStore = custodia.store.sqlite:SqliteStore', ] setup( name=about['__title__'], version=about['__version__'], description=about['__summary__'], long_description=long_description, license=about['__license__'], url=about['__uri__'], author=about['__author__'], author_email=about['__email__'], maintainer=about['__author__'], maintainer_email=about['__email__'], namespace_packages=['custodia'], package_dir={'': 'src'}, packages=[ 'custodia', 'custodia.cli', 'custodia.httpd', 'custodia.message', 'custodia.server', 'custodia.store', ], entry_points={ 'console_scripts': [ 'custodia = custodia.server:main', 'custodia-cli = custodia.cli:main', ], 'custodia.authenticators': custodia_authenticators, 'custodia.authorizers': custodia_authorizers, 'custodia.clients': custodia_clients, 'custodia.consumers': custodia_consumers, 'custodia.stores': custodia_stores, }, cmdclass={'version': Version}, classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Intended Audience :: Developers', 'Topic :: Security', 'Topic :: Software Development :: Libraries :: Python Modules' ], install_requires=requirements, tests_require=test_requires, extras_require=extras_require, ) custodia-0.5.0/src/000077500000000000000000000000001310463436300141215ustar00rootroot00000000000000custodia-0.5.0/src/custodia/000077500000000000000000000000001310463436300157345ustar00rootroot00000000000000custodia-0.5.0/src/custodia/__about__.py000066400000000000000000000011451310463436300202150ustar00rootroot00000000000000# Copyright (C) 2017 Custodia Project Contributors - see LICENSE file __all__ = [ '__title__', '__summary__', '__uri__', '__version__', '__version_info__', '__author__', '__email__', '__license__', '__copyright__', ] __title__ = 'custodia' __summary__ = 'A service to manage, retrieve and store secrets.' __uri__ = 'https://github.com/latchset/custodia' __version_info__ = (0, 5, 0) __version__ = '.'.join(str(v) for v in __version_info__) __author__ = 'Custodia project Contributors' __email__ = 'simo@redhat.com' __license__ = 'GPLv3+' __copyright__ = 'Copyright 2015-2017 {0}'.format(__author__) custodia-0.5.0/src/custodia/__init__.py000066400000000000000000000002131310463436300200410ustar00rootroot00000000000000# custodia namespace # You must NOT include any other code and data in __init__.py __import__('pkg_resources').declare_namespace(__name__) custodia-0.5.0/src/custodia/cli/000077500000000000000000000000001310463436300165035ustar00rootroot00000000000000custodia-0.5.0/src/custodia/cli/__init__.py000066400000000000000000000207421310463436300206210ustar00rootroot00000000000000# Copyright (C) 2016 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import, print_function import argparse import operator import os import traceback import pkg_resources from requests.exceptions import ConnectionError from requests.exceptions import HTTPError as RequestsHTTPError import six from custodia import log from custodia.client import CustodiaSimpleClient from custodia.compat import unquote, url_escape, urlparse if six.PY2: from StringIO import StringIO else: from io import StringIO try: from json import JSONDecodeError except ImportError: # Python <= 3.4 has no JSONDecodeError JSONDecodeError = ValueError log.warn_provisional(__name__) # exit codes E_HTTP_ERROR = 1 E_CONNECTION_ERROR = 2 E_JSON_ERROR = 3 E_OTHER = 100 main_parser = argparse.ArgumentParser( prog='custodia-cli', description='Custodia command line interface' ) def server_check(arg): """Check and format --server arg """ if arg.startswith(('http://', 'https://', 'http+unix://')): return arg if arg.startswith('./'): arg = os.path.abspath(arg) elif not arg.startswith('/'): raise argparse.ArgumentTypeError( 'Unix socket path must start with / or ./') # assume it is a unix socket return 'http+unix://{}'.format(url_escape(arg, '')) def instance_check(arg): if set(arg).intersection(':/@'): raise argparse.ArgumentTypeError( 'Instance name contains invalid characters') return arg def split_header(arg): name, value = arg.split('=') return name, value group = main_parser.add_mutually_exclusive_group() group.add_argument( '--server', type=server_check, help=('Custodia server location, supports http://, https://, ' 'or path to a unix socket.') ) group.add_argument( '--instance', default=os.getenv('CUSTODIA_INSTANCE', 'custodia'), type=instance_check, help="Instance name (default: CUSTODIA_INSTANCE or 'custodia')", ) main_parser.add_argument( '--uds-urlpath', type=str, default='/secrets/', help='URL path for Unix Domain Socket' ) main_parser.add_argument( '--header', type=split_header, action='append', help='Extra headers' ) main_parser.add_argument( '--verbose', action='store_true', ) main_parser.add_argument( '--debug', action='store_true', ) # TLS main_parser.add_argument( '--cafile', type=str, default=None, help='PEM encoded file with root CAs' ) main_parser.add_argument( '--certfile', type=str, default=None, help='PEM encoded file with certs for TLS client authentication' ) main_parser.add_argument( '--keyfile', type=str, default=None, help='PEM encoded key file (if not given, key is read from certfile)' ) # handlers def handle_name(args): client = args.client_conn func = getattr(client, args.command) return func(args.name) def handle_name_value(args): client = args.client_conn func = getattr(client, args.command) return func(args.name, args.value) # subparsers subparsers = main_parser.add_subparsers() subparsers.required = True parser_create_container = subparsers.add_parser( 'mkdir', help='Create a container') parser_create_container.add_argument('name', type=str, help='key') parser_create_container.set_defaults( func=handle_name, command='create_container', sub='mkdir', ) parser_delete_container = subparsers.add_parser( 'rmdir', help='Delete a container') parser_delete_container.add_argument('name', type=str, help='key') parser_delete_container.set_defaults( func=handle_name, command='delete_container', sub='rmdir', ) parser_list_container = subparsers.add_parser( 'ls', help='List content of a container') parser_list_container.add_argument('name', type=str, help='key') parser_list_container.set_defaults( func=handle_name, command='list_container', sub='ls', ) parser_get_secret = subparsers.add_parser( 'get', help='Get secret') parser_get_secret.add_argument('name', type=str, help='key') parser_get_secret.set_defaults( func=handle_name, command='get_secret', sub='get', ) parser_set_secret = subparsers.add_parser( 'set', help='Set secret') parser_set_secret.add_argument('name', type=str, help='key') parser_set_secret.add_argument('value', type=str, help='value') parser_set_secret.set_defaults( command='set_secret', func=handle_name_value, sub='set' ) parser_del_secret = subparsers.add_parser( 'del', help='Delete a secret') parser_del_secret.add_argument('name', type=str, help='key') parser_del_secret.set_defaults( func=handle_name, command='del_secret', sub='del', ) # plugins PLUGINS = [ 'custodia.authenticators', 'custodia.authorizers', 'custodia.clients', 'custodia.consumers', 'custodia.stores' ] def handle_plugins(args): result = [] errmsg = "**ERR** {0} ({1.__class__.__name__}: {1})" for plugin in PLUGINS: result.append('[{}]'.format(plugin)) eps = pkg_resources.iter_entry_points(plugin) eps = sorted(eps, key=operator.attrgetter('name')) for ep in eps: try: if hasattr(ep, 'resolve'): ep.resolve() else: ep.load(require=False) except Exception as e: # pylint: disable=broad-except if args.verbose: result.append(errmsg.format(ep, e)) else: result.append(str(ep)) result.append('') return result[:-1] parser_plugins = subparsers.add_parser( 'plugins', help='List plugins') parser_plugins.set_defaults( func=handle_plugins, command='plugins', sub='plugins', name=None, ) parser_plugins.add_argument( '--verbose', action='store_true', help="Verbose mode, show failing plugins." ) def error_message(args, exc): out = StringIO() parts = urlparse(args.server) if args.debug: traceback.print_exc(file=out) out.write('\n') out.write("ERROR: Custodia command '{args.sub} {args.name}' failed.\n") if args.verbose: out.write("Custodia server '{args.server}'.\n") if isinstance(exc, RequestsHTTPError): errcode = E_HTTP_ERROR out.write("{exc.__class__.__name__}: {exc}\n") elif isinstance(exc, ConnectionError): errcode = E_CONNECTION_ERROR if parts.scheme == 'http+unix': out.write("Failed to connect to Unix socket '{unix_path}':\n") else: out.write("Failed to connect to '{parts.netloc}' " "({parts.scheme}):\n") # ConnectionError always contains an inner exception out.write(" {exc.args[0]}\n") elif isinstance(exc, JSONDecodeError): errcode = E_JSON_ERROR out.write("Server returned invalid JSON response:\n") out.write(" {exc}\n") else: errcode = E_OTHER out.write("{exc.__class__.__name__}: {exc}\n") msg = out.getvalue() if not msg.endswith('\n'): msg += '\n' return errcode, msg.format(args=args, exc=exc, parts=parts, unix_path=unquote(parts.netloc)) def parse_args(arglist=None): args = main_parser.parse_args(arglist) if args.debug: args.verbose = True if not args.server: instance_socket = '/var/run/custodia/{}.sock'.format(args.instance) args.server = 'http+unix://{}'.format(url_escape(instance_socket, '')) if args.server.startswith('http+unix://'): # append uds-path if not args.server.endswith('/'): udspath = args.uds_urlpath if not udspath.startswith('/'): udspath = '/' + udspath args.server += udspath args.client_conn = CustodiaSimpleClient(args.server) if args.header is not None: args.client_conn.headers.update(args.header) if args.cafile: args.client_conn.set_ca_cert(args.cafile) if args.certfile: args.client_conn.set_client_cert(args.certfile, args.keyfile) args.client_conn.headers['CUSTODIA_CERT_AUTH'] = 'true' return args def main(): args = parse_args() log.setup_logging(debug=args.debug, auditfile=None) try: result = args.func(args) except BaseException as e: errcode, msg = error_message(args, e) main_parser.exit(errcode, msg) else: if result is not None: if isinstance(result, list): print('\n'.join(result)) else: print(result) if __name__ == '__main__': main() custodia-0.5.0/src/custodia/cli/__main__.py000066400000000000000000000002641310463436300205770ustar00rootroot00000000000000# Copyright (C) 2016 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import from custodia.cli import main if __name__ == '__main__': main() custodia-0.5.0/src/custodia/client.py000066400000000000000000000222361310463436300175710ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import import socket from jwcrypto.common import json_decode from jwcrypto.jwk import JWK import requests from requests.adapters import HTTPAdapter from requests.compat import unquote, urlparse from requests.packages.urllib3.connection import HTTPConnection from requests.packages.urllib3.connectionpool import HTTPConnectionPool from custodia.log import getLogger from custodia.message.kem import ( check_kem_claims, decode_enc_kem, make_enc_kem ) logger = getLogger(__name__) class HTTPUnixConnection(HTTPConnection): def __init__(self, host, timeout=60, **kwargs): # pylint: disable=bad-super-call super(HTTPConnection, self).__init__('localhost') self.unix_socket = host self.timeout = timeout def connect(self): s = socket.socket(family=socket.AF_UNIX) s.settimeout(self.timeout) s.connect(self.unix_socket) self.sock = s # pylint: disable=attribute-defined-outside-init class HTTPUnixConnectionPool(HTTPConnectionPool): scheme = 'http+unix' ConnectionCls = HTTPUnixConnection class HTTPUnixAdapter(HTTPAdapter): def get_connection(self, url, proxies=None): # proxies, silently ignored path = unquote(urlparse(url).netloc) return HTTPUnixConnectionPool(path) DEFAULT_HEADERS = {'Content-Type': 'application/json'} class CustodiaHTTPClient(object): def __init__(self, url): self.session = requests.Session() self.session.mount('http+unix://', HTTPUnixAdapter()) self.headers = dict(DEFAULT_HEADERS) self.url = url self._last_response = None def set_simple_auth_keys(self, name, key, name_header='CUSTODIA_AUTH_ID', key_header='CUSTODIA_AUTH_KEY'): self.headers[name_header] = name self.headers[key_header] = key def set_ca_cert(self, cafile): self.session.verify = cafile def set_client_cert(self, certfile, keyfile=None): if keyfile is None: self.session.cert = certfile else: self.session.cert = (certfile, keyfile) def _join_url(self, path): return self.url.rstrip('/') + '/' + path.lstrip('/') def _add_headers(self, **kwargs): headers = kwargs.get('headers', None) if headers is None: headers = dict() headers.update(self.headers) return headers def _request(self, cmd, path, **kwargs): self._last_response = None url = self._join_url(path) kwargs['headers'] = self._add_headers(**kwargs) logger.debug("%s %s", cmd.__name__.upper(), url) self._last_response = cmd(url, **kwargs) logger.debug("Response: %s", self._last_response) return self._last_response @property def last_response(self): return self._last_response def delete(self, path, **kwargs): return self._request(self.session.delete, path, **kwargs) def get(self, path, **kwargs): return self._request(self.session.get, path, **kwargs) def head(self, path, **kwargs): return self._request(self.session.head, path, **kwargs) def patch(self, path, **kwargs): return self._request(self.session.patch, path, **kwargs) def post(self, path, **kwargs): return self._request(self.session.post, path, **kwargs) def put(self, path, **kwargs): return self._request(self.session.put, path, **kwargs) def container_name(self, name): return name if name.endswith('/') else name + '/' def create_container(self, name): raise NotImplementedError def list_container(self, name): raise NotImplementedError def delete_container(self, name): raise NotImplementedError def get_secret(self, name): raise NotImplementedError def set_secret(self, name, value): raise NotImplementedError def del_secret(self, name): raise NotImplementedError class CustodiaSimpleClient(CustodiaHTTPClient): def create_container(self, name): r = self.post(self.container_name(name)) r.raise_for_status() def delete_container(self, name): r = self.delete(self.container_name(name)) r.raise_for_status() def list_container(self, name): r = self.get(self.container_name(name)) r.raise_for_status() return r.json() def get_secret(self, name): r = self.get(name) r.raise_for_status() simple = r.json() ktype = simple.get("type", None) if ktype != "simple": raise TypeError("Invalid key type: %s" % ktype) return simple["value"] def set_secret(self, name, value): r = self.put(name, json={"type": "simple", "value": value}) r.raise_for_status() def del_secret(self, name): r = self.delete(name) r.raise_for_status() class CustodiaKEMClient(CustodiaHTTPClient): def __init__(self, url): super(CustodiaKEMClient, self).__init__(url) self._cli_signing_key = None self._cli_decryption_key = None self._srv_verifying_key = None self._srv_encryption_key = None self._sig_alg = None self._enc_alg = None def _decode_key(self, key): if key is None: return None elif isinstance(key, JWK): return key elif isinstance(key, dict): return JWK(**key) elif isinstance(key, str): return JWK(**(json_decode(key))) else: raise TypeError("Invalid key type") def set_server_public_keys(self, sig, enc): self._srv_verifying_key = self._decode_key(sig) self._srv_encryption_key = self._decode_key(enc) def set_client_keys(self, sig, enc): self._cli_signing_key = self._decode_key(sig) self._cli_decryption_key = self._decode_key(enc) def set_algorithms(self, sig, enc): self._sig_alg = sig self._enc_alg = enc def _signing_algorithm(self, key): if self._sig_alg is not None: return self._sig_alg elif key.key_type == 'RSA': return 'RS256' elif key.key_type == 'EC': return 'ES256' else: raise ValueError('Unsupported key type') def _encryption_algorithm(self, key): if self._enc_alg is not None: return self._enc_alg elif key.key_type == 'RSA': return ('RSA-OAEP', 'A256CBC-HS512') elif key.key_type == 'EC': return ('ECDH-ES+A256KW', 'A256CBC-HS512') else: raise ValueError('Unsupported key type') def _kem_wrap(self, name, value): if self._cli_signing_key is None: raise KeyError("Client Signing key is not available") if self._srv_encryption_key is None: raise KeyError("Server Encryption key is not available") sig_alg = self._signing_algorithm(self._cli_signing_key) enc_alg = self._encryption_algorithm(self._srv_encryption_key) return make_enc_kem(name, value, self._cli_signing_key, sig_alg, self._srv_encryption_key, enc_alg) def _kem_unwrap(self, name, message): if message.get("type", None) != "kem": raise TypeError("Invalid token type, expected 'kem', got %s" % ( message.get("type", None),)) if self._cli_decryption_key is None: raise KeyError("Client Decryption key is not available") if self._srv_verifying_key is None: raise KeyError("Server Verifying key is not available") claims = decode_enc_kem(message["value"], self._cli_decryption_key, self._srv_verifying_key) check_kem_claims(claims, name) return claims def create_container(self, name): cname = self.container_name(name) message = self._kem_wrap(cname, None) r = self.post(cname, json={"type": "kem", "value": message}) r.raise_for_status() self._kem_unwrap(cname, r.json()) def delete_container(self, name): cname = self.container_name(name) message = self._kem_wrap(cname, None) r = self.delete(cname, json={"type": "kem", "value": message}) r.raise_for_status() self._kem_unwrap(cname, r.json()) def list_container(self, name): return self.get_secret(self.container_name(name)) def get_secret(self, name): message = self._kem_wrap(name, None) r = self.get(name, params={"type": "kem", "value": message}) r.raise_for_status() claims = self._kem_unwrap(name, r.json()) return claims['value'] def set_secret(self, name, value): message = self._kem_wrap(name, value) r = self.put(name, json={"type": "kem", "value": message}) r.raise_for_status() self._kem_unwrap(name, r.json()) def del_secret(self, name): message = self._kem_wrap(name, None) r = self.delete(name, json={"type": "kem", "value": message}) r.raise_for_status() self._kem_unwrap(name, r.json()) custodia-0.5.0/src/custodia/compat.py000066400000000000000000000012751310463436300175760ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file """Python 2/3 compatibility """ # pylint: disable=no-name-in-module,import-error from __future__ import absolute_import import six if six.PY2: # use https://pypi.python.org/pypi/configparser/ on Python 2 from backports import configparser from urllib import quote as url_escape from urllib import quote_plus, unquote from urlparse import parse_qs, urlparse else: import configparser from urllib.parse import quote as url_escape from urllib.parse import parse_qs, quote_plus, unquote, urlparse __all__ = ( 'configparser', 'parse_qs', 'quote_plus', 'unquote', 'url_escape', 'urlparse' ) custodia-0.5.0/src/custodia/forwarder.py000066400000000000000000000066561310463436300203160ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import import uuid from custodia.client import CustodiaHTTPClient from custodia.plugin import HTTPConsumer, HTTPError from custodia.plugin import INHERIT_GLOBAL, PluginOption, REQUIRED class Forwarder(HTTPConsumer): forward_uri = PluginOption(str, REQUIRED, None) tls_cafile = PluginOption(str, INHERIT_GLOBAL(None), 'Path to CA file') tls_certfile = PluginOption( str, None, 'Path to cert file for client cert auth') tls_keyfile = PluginOption( str, None, 'Path to key file for client cert auth') forward_headers = PluginOption('json', '{}', None) prefix_remote_user = PluginOption(bool, True, None) def __init__(self, config, section): super(Forwarder, self).__init__(config, section) self.client = CustodiaHTTPClient(self.forward_uri) if self.tls_certfile is not None: self.client.set_client_cert(self.tls_certfile, self.tls_keyfile) if self.tls_cafile is not None: self.client.set_ca_cert(self.tls_cafile) self.uuid = str(uuid.uuid4()) # pylint: disable=unsubscriptable-object # pylint: disable=unsupported-assignment-operation self.forward_headers['X-LOOP-CUSTODIA'] = self.uuid def _path(self, request): trail = request.get('trail', []) if self.prefix_remote_user: prefix = [request.get('remote_user', 'guest').rstrip('/')] else: prefix = [] return '/'.join(prefix + trail) def _headers(self, request): headers = {} headers.update(self.forward_headers) loop = request['headers'].get('X-LOOP-CUSTODIA', None) if loop is not None: headers['X-LOOP-CUSTODIA'] += ',' + loop return headers def _response(self, reply, response): if reply.status_code < 200 or reply.status_code > 299: raise HTTPError(reply.status_code) response['code'] = reply.status_code if reply.content: response['output'] = reply.content def _request(self, cmd, request, response, path, **kwargs): if self.uuid in request['headers'].get('X-LOOP-CUSTODIA', ''): raise HTTPError(502, "Loop detected") reply = cmd(path, **kwargs) self._response(reply, response) def GET(self, request, response): self._request(self.client.get, request, response, self._path(request), params=request.get('query', None), headers=self._headers(request)) def PUT(self, request, response): self._request(self.client.put, request, response, self._path(request), data=request.get('body', None), params=request.get('query', None), headers=self._headers(request)) def DELETE(self, request, response): self._request(self.client.delete, request, response, self._path(request), params=request.get('query', None), headers=self._headers(request)) def POST(self, request, response): self._request(self.client.post, request, response, self._path(request), data=request.get('body', None), params=request.get('query', None), headers=self._headers(request)) custodia-0.5.0/src/custodia/httpd/000077500000000000000000000000001310463436300170575ustar00rootroot00000000000000custodia-0.5.0/src/custodia/httpd/__init__.py000066400000000000000000000000001310463436300211560ustar00rootroot00000000000000custodia-0.5.0/src/custodia/httpd/authenticators.py000066400000000000000000000117031310463436300224700ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import import os from cryptography.hazmat.primitives import constant_time from custodia import log from custodia.plugin import HTTPAuthenticator, PluginOption class SimpleCredsAuth(HTTPAuthenticator): uid = PluginOption('pwd_uid', -1, "User id or name, -1 ignores user") gid = PluginOption('grp_gid', -1, "Group id or name, -1 ignores group") def handle(self, request): creds = request.get('creds') if creds is None: self.logger.debug('SCA: Missing "creds" from request') return False uid = int(creds['uid']) gid = int(creds['gid']) uid_match = self.uid != -1 and self.uid == uid gid_match = self.gid != -1 and self.gid == gid if uid_match or gid_match: self.audit_svc_access(log.AUDIT_SVC_AUTH_PASS, request['client_id'], "%d, %d" % (uid, gid)) return True else: self.audit_svc_access(log.AUDIT_SVC_AUTH_FAIL, request['client_id'], "%d, %d" % (uid, gid)) return False class SimpleHeaderAuth(HTTPAuthenticator): header = PluginOption(str, 'REMOTE_USER', "header name") value = PluginOption('str_set', None, "Comma-separated list of required values") def handle(self, request): if self.header not in request['headers']: self.logger.debug('SHA: No "headers" in request') return None value = request['headers'][self.header] if self.value is not None: # pylint: disable=unsupported-membership-test if value not in self.value: self.audit_svc_access(log.AUDIT_SVC_AUTH_FAIL, request['client_id'], value) return False self.audit_svc_access(log.AUDIT_SVC_AUTH_PASS, request['client_id'], value) request['remote_user'] = value return True class SimpleAuthKeys(HTTPAuthenticator): id_header = PluginOption(str, 'CUSTODIA_AUTH_ID', "auth id header name") key_header = PluginOption(str, 'CUSTODIA_AUTH_KEY', "auth key header name") store = PluginOption('store', None, None) store_namespace = PluginOption(str, 'custodiaSAK', "") def _db_key(self, name): return os.path.join(self.store_namespace, name) def handle(self, request): name = request['headers'].get(self.id_header, None) key = request['headers'].get(self.key_header, None) if name is None and key is None: self.logger.debug('Ignoring request no relevant headers provided') return None validated = False try: val = self.store.get(self._db_key(name)) if val is None: raise ValueError("No such ID") if constant_time.bytes_eq(val.encode('utf-8'), key.encode('utf-8')): validated = True except Exception: # pylint: disable=broad-except self.audit_svc_access(log.AUDIT_SVC_AUTH_FAIL, request['client_id'], name) return False if validated: self.audit_svc_access(log.AUDIT_SVC_AUTH_PASS, request['client_id'], name) request['remote_user'] = name return True self.audit_svc_access(log.AUDIT_SVC_AUTH_FAIL, request['client_id'], name) return False class SimpleClientCertAuth(HTTPAuthenticator): header = PluginOption(str, 'CUSTODIA_CERT_AUTH', "header name") def handle(self, request): cert_auth = request['headers'].get(self.header, "false").lower() client_cert = request['client_cert'] # {} or None if not client_cert or cert_auth not in {'1', 'yes', 'true', 'on'}: self.logger.debug('Ignoring request no relevant header or cert' ' provided') return None subject = client_cert.get('subject', {}) dn = [] name = None # TODO: check SAN first for rdn in subject: for key, value in rdn: dn.append('{}="{}"'.format(key, value.replace('"', r'\"'))) if key == 'commonName': name = value break dn = ', '.join(dn) self.logger.debug('Client cert subject: {}, serial: {}'.format( dn, client_cert.get('serialNumber'))) if name: self.audit_svc_access(log.AUDIT_SVC_AUTH_PASS, request['client_id'], name) request['remote_user'] = name return True self.audit_svc_access(log.AUDIT_SVC_AUTH_FAIL, request['client_id'], dn) return False custodia-0.5.0/src/custodia/httpd/authorizers.py000066400000000000000000000054611310463436300220160ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import import os from custodia import log from custodia.plugin import HTTPAuthorizer, PluginOption class SimplePathAuthz(HTTPAuthorizer): # keep SimplePathAuthz an old-style plugin for now. # KEMKeysStore and IPAKEMKeys haven't been ported. def __init__(self, config): super(SimplePathAuthz, self).__init__(config) self.paths = [] if 'paths' in self.config: self.paths = self.config['paths'].split() def handle(self, request): reqpath = path = request.get('path', '') # if an authorized path does not end in / # check if it matches fullpath for strict match for authz in self.paths: # pylint: disable=not-an-iterable if authz.endswith('/'): continue if authz.endswith('.'): # special case to match a path ending in / authz = authz[:-1] if authz == path: self.audit_svc_access(log.AUDIT_SVC_AUTHZ_PASS, request['client_id'], path) return True while path != '': # pylint: disable=unsupported-membership-test if path in self.paths: self.audit_svc_access(log.AUDIT_SVC_AUTHZ_PASS, request['client_id'], path) return True if path == '/': path = '' else: path, _ = os.path.split(path) self.logger.debug('No path in %s matched %s', self.paths, reqpath) return None class UserNameSpace(HTTPAuthorizer): path = PluginOption(str, '/', 'User namespace path') store = PluginOption('store', None, None) def handle(self, request): # Only check if we are in the right (sub)path path = request.get('path', '/') if not path.startswith(self.path): self.logger.debug('%s is not contained in %s', path, self.path) return None name = request.get('remote_user', None) if name is None: # UserNameSpace requires a user ... self.audit_svc_access(log.AUDIT_SVC_AUTHZ_FAIL, request['client_id'], path) return False # pylint: disable=no-member namespace = self.path.rstrip('/') + '/' + name + '/' if not path.startswith(namespace): # Not in the namespace self.audit_svc_access(log.AUDIT_SVC_AUTHZ_FAIL, request['client_id'], path) return False request['default_namespace'] = name self.audit_svc_access(log.AUDIT_SVC_AUTHZ_PASS, request['client_id'], path) return True custodia-0.5.0/src/custodia/httpd/consumer.py000066400000000000000000000006241310463436300212660ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import import warnings from custodia.plugin import DEFAULT_CTYPE, HTTPConsumer, SUPPORTED_COMMANDS __all__ = ('DEFAULT_CTYPE', 'SUPPORTED_COMMANDS', 'HTTPConsumer') warnings.warn('custodia.httpd.consumer is deprecated, import from ' 'custodia.plugin instead.', DeprecationWarning) custodia-0.5.0/src/custodia/httpd/server.py000066400000000000000000000471711310463436300207510ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import import atexit import errno import os import shutil import socket import ssl import struct import sys import warnings import six from custodia import log from custodia.compat import parse_qs, unquote, urlparse from custodia.plugin import HTTPError # pylint: disable=import-error,no-name-in-module if six.PY2: from BaseHTTPServer import BaseHTTPRequestHandler from SocketServer import ForkingTCPServer, BaseServer else: from http.server import BaseHTTPRequestHandler from socketserver import ForkingTCPServer, BaseServer # pylint: enable=import-error,no-name-in-module try: from systemd import daemon as sd # pylint: disable=import-error except ImportError: sd = None if 'NOTIFY_SOCKET' in os.environ: warnings.warn( "NOTIFY_SOCKET env var is set but python-systemd bindings are " "not available!", category=RuntimeWarning ) if 'LISTEN_FDS' in os.environ: warnings.warn( "LISTEN_FDS env var is set, but python-systemd bindings are" "not available!", category=RuntimeWarning ) logger = log.getLogger(__name__) SO_PEERCRED = getattr(socket, 'SO_PEERCRED', 17) SO_PEERSEC = getattr(socket, 'SO_PEERSEC', 31) SELINUX_CONTEXT_LEN = 256 MAX_REQUEST_SIZE = 10 * 1024 * 1024 # For now limit body to 10MiB class ForkingHTTPServer(ForkingTCPServer): """ A forking HTTP Server. Each request runs into a forked server so that the whole environment is clean and isolated, and parallel requests cannot unintentionally influence one another. When a request is received it is parsed by the handler_class provided at server initialization. """ server_string = "Custodia/0.1" allow_reuse_address = True socket_file = None def __init__(self, server_address, handler_class, config, bind_and_activate=True): # pylint: disable=super-init-not-called, non-parent-init-called # Init just BaseServer, TCPServer creates a socket. BaseServer.__init__(self, server_address, handler_class) if isinstance(server_address, socket.socket): # It's a bound and activates socket from systemd. self.socket = server_address bind_and_activate = False else: self.socket = socket.socket(self.address_family, self.socket_type) # copied from TCPServer if bind_and_activate: try: self.server_bind() self.server_activate() except: self.server_close() raise if self.socket.family == socket.AF_UNIX: self.socket_file = self.socket.getsockname() if 'consumers' not in config: raise ValueError('Configuration does not provide any consumer') self.config = config if 'server_string' in self.config: self.server_string = self.config['server_string'] self.auditlog = log.auditlog class ForkingUnixHTTPServer(ForkingHTTPServer): address_family = socket.AF_UNIX def server_bind(self): self.unlink() # Remove on exit atexit.register(self.unlink) basedir = os.path.dirname(self.server_address) if not os.path.isdir(basedir): os.makedirs(basedir, mode=0o755) ForkingHTTPServer.server_bind(self) os.chmod(self.server_address, 0o666) def unlink(self): try: os.unlink(self.server_address) except OSError: pass class ForkingTLSServer(ForkingHTTPServer): def __init__(self, server_address, handler_class, config, context=None): ForkingHTTPServer.__init__(self, server_address, handler_class, config) self._context = context if context is not None else self._mkcontext() def _mkcontext(self): certfile = self.config.get('tls_certfile') keyfile = self.config.get('tls_keyfile') cafile = self.config.get('tls_cafile') capath = self.config.get('tls_capath') if self.config.get('tls_verify_client', False): verifymode = ssl.CERT_REQUIRED else: verifymode = ssl.CERT_NONE if not certfile: raise ValueError('tls_certfile is not set.') context = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH, cafile=cafile, capath=capath) context.load_cert_chain(certfile, keyfile) context.verify_mode = verifymode return context def get_request(self): conn, client_addr = self.socket.accept() sslconn = self._context.wrap_socket(conn, server_side=True) return sslconn, client_addr class HTTPRequestHandler(BaseHTTPRequestHandler): """ This request handler is a slight modification of BaseHTTPRequestHandler where the per-request handler is replaced. When a request comes in it is parsed and the 'request' dictionary is populated accordingly. Additionally a 'creds' structure is added to the request. The 'creds' structure contains the data retrieved via a call to getsockopt with the SO_PEERCRED option. This retrieves via kernel assist the uid,gid and pid of the process on the other side of the unix socket on which the request has been made. This can be used for authentication and/or authorization purposes. The 'creds' structure is further augmented with a 'context' option containing the Selinux Context string for the calling process, if available. after the request is parsed the server's pipeline() function is invoked in order to handle it. The pipeline() should return a response object, where te return 'code', the 'output' and 'headers' may be found. If no 'code' is present the request is assumed to be successful and a '200 OK' status code will be sent back to the client. The 'output' parameter can be a string or a file like object. The 'headers' objct must be a dictionary where keys are headers names. By default we assume HTTP1.0 """ protocol_version = "HTTP/1.0" def __init__(self, request, client_address, server): self.requestline = '' self.request_version = '' self.command = '' self.raw_requestline = None self.close_connection = 0 self.path = None # quoted, raw path self.path_chain = None # tuple of unquoted segments self.query = None self.url = None self.body = None self.loginuid = None self._creds = False BaseHTTPRequestHandler.__init__(self, request, client_address, server) def version_string(self): return self.server.server_string def _get_loginuid(self, pid): loginuid = None # NOTE: Using proc to find the login uid is not reliable # this is why login uid is fetched separately and not stored # into 'creds', to avoid giving the false impression it can be # used to perform access control decisions try: with open("/proc/%i/loginuid" % pid, "r") as f: loginuid = int(f.read()) except IOError as e: if e.errno != errno.ENOENT: raise if loginuid == -1: loginuid = None return loginuid @property def peer_creds(self): if self._creds is not False: return self._creds # works only for unix sockets if self.request.family != socket.AF_UNIX: self._creds = None return self._creds # pid_t: signed int32, uid_t/gid_t: unsigned int32 fmt = 'iII' creds = self.request.getsockopt(socket.SOL_SOCKET, SO_PEERCRED, struct.calcsize(fmt)) pid, uid, gid = struct.unpack(fmt, creds) try: creds = self.request.getsockopt(socket.SOL_SOCKET, SO_PEERSEC, SELINUX_CONTEXT_LEN) context = creds.rstrip(b'\x00').decode('utf-8') except Exception: # pylint: disable=broad-except logger.debug("Couldn't retrieve SELinux Context", exc_info=True) context = None self._creds = {'pid': pid, 'uid': uid, 'gid': gid, 'context': context} return self._creds @property def peer_info(self): if self.peer_creds is not None: return self._creds['pid'] elif self.request.family in {socket.AF_INET, socket.AF_INET6}: return self.request.getpeername() return None @property def peer_cert(self): if not hasattr(self.request, 'getpeercert'): return None return self.request.getpeercert() def parse_request(self): if not BaseHTTPRequestHandler.parse_request(self): return False # grab the loginuid from `/proc` as soon as possible creds = self.peer_creds if creds is not None: self.loginuid = self._get_loginuid(creds['pid']) # after basic parsing also use urlparse to retrieve individual # elements of a request. url = urlparse(self.path) # Yes, override path with the path part only self.path = url.path self.path_chain = self._parse_path(url) # Create dict out of query self.query = parse_qs(url.query) # keep the rest into the 'url' element in case someone needs it self.url = url return True def _parse_path(self, url): path_chain = [] for segment in url.path.split('/'): # unquote URL path encoding segment = unquote(segment) path_chain.append(segment) return tuple(path_chain) def parse_body(self): length = int(self.headers.get('content-length', 0)) if length > MAX_REQUEST_SIZE: raise HTTPError(413) if length == 0: self.body = None else: self.body = self.rfile.read(length) def handle_one_request(self): if self.request.family == socket.AF_UNIX: # Set a fake client address to make log functions happy self.client_address = ['127.0.0.1', 0] try: if not self.server.config: self.close_connection = 1 return self.raw_requestline = self.rfile.readline(65537) if not self.raw_requestline: self.close_connection = 1 return if len(self.raw_requestline) > 65536: self.requestline = '' self.request_version = '' self.command = '' self.send_error(414) self.wfile.flush() return if not self.parse_request(): self.close_connection = 1 return try: self.parse_body() except HTTPError as e: self.send_error(e.code, e.mesg) self.wfile.flush() return request = {'creds': self.peer_creds, 'client_cert': self.peer_cert, 'client_id': self.peer_info, 'command': self.command, 'path': self.path, 'path_chain': self.path_chain, 'query': self.query, 'url': self.url, 'version': self.request_version, 'headers': self.headers, 'body': self.body} logger.debug( "REQUEST: %s %s, query: %r, cred: %r, client_id: %s, " "headers: %r, body: %r", request['command'], request['path_chain'], request['query'], request['creds'], request['client_id'], dict(request['headers']), request['body'] ) try: response = self.pipeline(self.server.config, request) if response is None: raise HTTPError(500) except HTTPError as e: self.send_error(e.code, e.mesg) self.wfile.flush() return except socket.timeout as e: self.log_error("Request timed out: %r", e) self.close_connection = 1 return except Exception as e: # pylint: disable=broad-except self.log_error("Handler failed: %r", e, exc_info=True) self.send_error(500) self.wfile.flush() return self.send_response(response.get('code', 200)) for header, value in six.iteritems(response.get('headers', {})): self.send_header(header, value) self.end_headers() output = response.get('output', None) if hasattr(output, 'read'): shutil.copyfileobj(output, self.wfile) output.close() elif output is not None: self.wfile.write(output) else: self.close_connection = 1 self.wfile.flush() return except socket.timeout as e: self.log_error("Request timed out: %r", e) self.close_connection = 1 return # pylint: disable=arguments-differ def log_error(self, fmtstr, *args, **kwargs): logger.error(fmtstr, *args, **kwargs) def pipeline(self, config, request): """ The pipeline() function handles authentication and invocation of the correct consumer based on the server configuration, that is provided at initialization time. When authentication is performed all the authenticators are executed. If any returns False, authentication fails and a 403 error is raised. If none of them positively succeeds and they all return None then also authentication fails and a 403 error is raised. Authentication plugins can add attributes to the request object for use of authorization or other plugins. When authorization is performed and positive result will cause the operation to be accepted and any negative result will cause it to fail. If no authorization plugin returns a positive result a 403 error is returned. Once authentication and authorization are successful the pipeline will parse the path component and find the consumer plugin that handles the provided path walking up the path component by component until a consumer is found. Paths are walked up from the leaf to the root, so if two consumers hang on the same tree, the one closer to the leaf will be used. If there is a trailing path when the conumer is selected then it will be stored in the request dicstionary named 'trail'. The 'trail' is an ordered list of the path components below the consumer entry point. """ path_chain = request['path_chain'] if not path_chain or path_chain[0] != '': # no path or not an absolute path raise HTTPError(400) # auth framework here authers = config.get('authenticators') if authers is None: raise HTTPError(403) valid_once = False for auth in authers: valid = authers[auth].handle(request) if valid is False: raise HTTPError(403) elif valid is True: valid_once = True if valid_once is not True: self.server.auditlog.svc_access(self.__class__.__name__, log.AUDIT_SVC_AUTH_FAIL, request['client_id'], 'No auth') raise HTTPError(403) # auhz framework here authzers = config.get('authorizers') if authzers is None: raise HTTPError(403) authz_ok = None for authz in authzers: valid = authzers[authz].handle(request) if valid is True: authz_ok = True elif valid is False: authz_ok = False break if authz_ok is not True: self.server.auditlog.svc_access(self.__class__.__name__, log.AUDIT_SVC_AUTHZ_FAIL, request['client_id'], path_chain) raise HTTPError(403) # Select consumer trail = [] while path_chain: if path_chain in config['consumers']: con = config['consumers'][path_chain] if len(trail) != 0: request['trail'] = trail return con.handle(request) trail.insert(0, path_chain[-1]) path_chain = path_chain[:-1] raise HTTPError(404) class HTTPServer(object): handler = HTTPRequestHandler def __init__(self, srvurl, config): url = urlparse(srvurl) serverclass, address = self._get_serverclass(url) if sd is not None: address = self._get_systemd_socket(address) self.httpd = serverclass(address, self.handler, config) def _get_serverclass(self, url): if url.scheme == 'http+unix': # Unix socket address = unquote(url.netloc) if not address: raise ValueError('Empty address {}'.format(url)) logger.info('Serving on Unix socket %s', address) serverclass = ForkingUnixHTTPServer elif url.scheme == 'http': host, port = url.netloc.split(":") address = (host, int(port)) logger.info('Serving on %s (HTTP)', url.netloc) serverclass = ForkingHTTPServer elif url.scheme == 'https': host, port = url.netloc.split(":") address = (host, int(port)) logger.info('Serving on %s (HTTPS)', url.netloc) serverclass = ForkingTLSServer else: raise ValueError('Unknown URL Scheme: %s' % url.scheme) return serverclass, address def _get_systemd_socket(self, address): fds = sd.listen_fds() if not fds: return address elif len(fds) > 1: raise ValueError('Too many listening sockets', fds) if isinstance(address, tuple): port = address[1] # systemd uses IPv6 if not sd.is_socket_inet(fds[0], family=socket.AF_INET6, type=socket.SOCK_STREAM, listening=True, port=port): raise ValueError("FD {} is not TCP IPv6 socket on port {}", fds[0], port) logger.info('Using systemd socket activation on port %i', port) sock = socket.fromfd(fds[0], socket.AF_INET6, socket.SOCK_STREAM) else: if not sd.is_socket_unix(fds[0], socket.SOCK_STREAM, listening=True, path=address): raise ValueError("FD {} is not Unix stream socket on path {}", fds[0], address) logger.info('Using systemd socket activation on path %s', address) sock = socket.fromfd(fds[0], socket.AF_UNIX, socket.SOCK_STREAM) if sys.version_info[0] < 3: # Python 2.7's socket.fromfd() returns _socket.socket sock = socket.socket(_sock=sock) return sock def get_socket(self): return (self.httpd.socket, self.httpd.socket_file) def serve(self): if sd is not None and sd.booted(): sd.notify("READY=1") return self.httpd.serve_forever() custodia-0.5.0/src/custodia/log.py000066400000000000000000000145711310463436300170770ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import import logging import sys import warnings import six LOGGING_FORMAT = "%(asctime)s - %(origin)-32s - %(message)s" LOGGING_DATEFORMAT = "%Y-%m-%d %H:%M:%S" class OriginContextFilter(logging.Filter): """Context filter to include 'origin' attribute in record """ def filter(self, record): if not hasattr(record, 'origin'): record.origin = record.name.split('.')[-1] return True class CustodiaFormatter(logging.Formatter): def format(self, record): # customize record.exc_text, Formatter.format() does not modify # exc_text when it has been set before. short_exc = False if record.exc_info and not record.exc_text: if getattr(record, "exc_fullstack", True): record.exc_text = self.formatException(record.exc_info) else: short_exc = True record.exc_text = u"{0.__name__}: {1}".format( record.exc_info[0], record.exc_info[1] ) result = super(CustodiaFormatter, self).format(record) if short_exc: # format() adds \n between message and exc_text text, exc = result.rsplit(u'\n', 1) return u"{0} ({1})".format(text, exc) else: return result class CustodiaLoggingAdapter(logging.LoggerAdapter): def __init__(self, plugin, debug): logger = logging.getLogger( '{0.__class__.__module__}.{0.__class__.__name__}'.format(plugin) ) logger.setLevel(logging.DEBUG if debug else logging.INFO) extra = {'origin': plugin.origin} super(CustodiaLoggingAdapter, self).__init__(logger, extra=extra) def exception(self, msg, *args, **kwargs): """Like standard exception() logger but only print stack in debug mode """ extra = kwargs.setdefault('extra', {}) extra['exc_fullstack'] = self.isEnabledFor(logging.DEBUG) kwargs['exc_info'] = True self.log(logging.ERROR, msg, *args, **kwargs) def getLogger(name): """Create logger with custom exception() method """ def exception(self, msg, *args, **kwargs): extra = kwargs.setdefault('extra', {}) extra['exc_fullstack'] = self.isEnabledFor(logging.DEBUG) kwargs['exc_info'] = True self.log(logging.ERROR, msg, *args, **kwargs) logger = logging.getLogger(name) logger.exception = six.create_bound_method(exception, logger) return logger def setup_logging(debug=False, auditfile=None, handler=None): root_logger = logging.getLogger() # default is stream handler to stderr if handler is None: handler = logging.StreamHandler(sys.stderr) # remove handler instance from root handler to prevent multiple # output handlers. handler_cls = type(handler) root_logger.handlers[:] = list( h for h in root_logger.handlers if not isinstance(h, handler_cls) ) # configure handler handler.setFormatter(CustodiaFormatter( fmt=LOGGING_FORMAT, datefmt=LOGGING_DATEFORMAT )) handler.addFilter(OriginContextFilter()) root_logger.addHandler(handler) # set logging level custodia_logger = getLogger('custodia') if debug: custodia_logger.setLevel(logging.DEBUG) custodia_logger.debug('Custodia debug logger enabled') # If the global debug is enabled, turn debug on in all 'custodia.*' # loggers logdict = logging.Logger.manager.loggerDict for name, obj in logdict.items(): if not isinstance(obj, logging.Logger): continue if name.startswith('custodia.'): obj.setLevel(logging.DEBUG) else: custodia_logger.setLevel(logging.INFO) # setup file handler for audit log audit_logger = logging.getLogger('custodia.audit') if auditfile is not None and len(audit_logger.handlers) == 0: audit_fmt = logging.Formatter(LOGGING_FORMAT, LOGGING_DATEFORMAT) audit_hdrl = logging.FileHandler(auditfile) audit_hdrl.setFormatter(audit_fmt) audit_logger.addHandler(audit_hdrl) custodia_logger.debug('Custodia audit log: %s', auditfile) AUDIT_NONE = 0 AUDIT_GET_ALLOWED = 1 AUDIT_GET_DENIED = 2 AUDIT_SET_ALLOWED = 3 AUDIT_SET_DENIED = 4 AUDIT_DEL_ALLOWED = 5 AUDIT_DEL_DENIED = 6 AUDIT_LAST = 7 AUDIT_SVC_NONE = 8 AUDIT_SVC_AUTH_PASS = 9 AUDIT_SVC_AUTH_FAIL = 10 AUDIT_SVC_AUTHZ_PASS = 11 AUDIT_SVC_AUTHZ_FAIL = 12 AUDIT_SVC_LAST = 13 AUDIT_MESSAGES = [ "AUDIT FAILURE", "ALLOWED: '%(client)s' requested key '%(key)s'", # AUDIT_GET_ALLOWED "DENIED: '%(client)s' requested key '%(key)s'", # AUDIT_GET_DENIED "ALLOWED: '%(client)s' stored key '%(key)s'", # AUDIT_SET_ALLOWED "DENIED: '%(client)s' stored key '%(key)s'", # AUDIT_SET_DENIED "ALLOWED: '%(client)s' deleted key '%(key)s'", # AUDIT_DEL_ALLOWED "DENIED: '%(client)s' deleted key '%(key)s'", # AUDIT_DEL_DENIED "AUDIT FAILURE 7", "AUDIT FAILURE 8", "PASS: '%(cli)s' authenticated as '%(name)s'", # SVC_AUTH_PASS "FAIL: '%(cli)s' authenticated as '%(name)s'", # SVC_AUTH_FAIL "PASS: '%(cli)s' authorized for '%(name)s'", # SVC_AUTHZ_PASS "FAIL: '%(cli)s' authorized for '%(name)s'", # SVC_AUTHZ_FAIL "AUDIT FAILURE 13", ] class AuditLog(object): def __init__(self, logger): self.logger = logger def key_access(self, origin, action, client, keyname): if action <= AUDIT_NONE or action >= AUDIT_LAST: action = AUDIT_NONE msg = AUDIT_MESSAGES[action] args = {'client': client, 'key': keyname} self.logger.info(msg, args, extra={'origin': origin}) def svc_access(self, origin, action, client, name): if action <= AUDIT_SVC_NONE or action >= AUDIT_SVC_LAST: action = AUDIT_NONE msg = AUDIT_MESSAGES[action] args = {'cli': client, 'name': name} self.logger.info(msg, args, extra={'origin': origin}) auditlog = AuditLog(logging.getLogger('custodia.audit')) class ProvisionalWarning(FutureWarning): pass def warn_provisional(modulename, stacklevel=3): msg = ("Module '{}' is a provisional API. It may changed or get " "removed in future releases.") return warnings.warn(msg.format(modulename), ProvisionalWarning, stacklevel=stacklevel) custodia-0.5.0/src/custodia/message/000077500000000000000000000000001310463436300173605ustar00rootroot00000000000000custodia-0.5.0/src/custodia/message/__init__.py000066400000000000000000000000001310463436300214570ustar00rootroot00000000000000custodia-0.5.0/src/custodia/message/common.py000066400000000000000000000032311310463436300212210ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import from custodia.log import getLogger logger = getLogger(__name__) class InvalidMessage(Exception): """Invalid Message. This exception is raised when a message cannot be parsed or validated. """ def __init__(self, message=None): logger.debug(message) super(InvalidMessage, self).__init__(message) class UnknownMessageType(Exception): """Unknown Message Type. This exception is raised when a message is of an unknown type. """ def __init__(self, message=None): logger.debug(message) super(UnknownMessageType, self).__init__(message) class UnallowedMessage(Exception): """Unallowed Message. This exception is raise when the message type is know but is not allowed. """ def __init__(self, message=None): logger.debug(message) super(UnallowedMessage, self).__init__(message) class MessageHandler(object): def __init__(self, request): self.req = request self.name = None self.payload = None self.msg_type = None def parse(self, msg, name): """Parses the message. :param req: the original request :param msg: a decoded json string with the incoming message :raises InvalidMessage: if the message cannot be parsed or validated """ raise NotImplementedError def reply(self, output): """Generates a reply. :param req: the original request :param output: a Python object that can be converted to JSON """ raise NotImplementedError custodia-0.5.0/src/custodia/message/formats.py000066400000000000000000000040041310463436300214030ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import from custodia.message.common import InvalidMessage from custodia.message.common import UnallowedMessage from custodia.message.common import UnknownMessageType from custodia.message.kem import KEMHandler from custodia.message.simple import SimpleKey default_types = ['simple', 'kem'] key_types = {'simple': SimpleKey, 'kem': KEMHandler} class Validator(object): """Validates incoming messages.""" def __init__(self, allowed=None): """Creates a Validator object. :param allowed: list of allowed message types (optional) """ self.allowed = allowed or default_types self.types = key_types.copy() def add_types(self, types): self.types.update(types) def parse(self, request, msg, name): if not isinstance(msg, dict): raise InvalidMessage('The message must be a dict') if 'type' not in msg: raise InvalidMessage('The type is missing') if isinstance(msg['type'], list): if len(msg['type']) != 1: raise InvalidMessage('Type is multivalued: %s' % msg['type']) msg_type = msg['type'][0] else: msg_type = msg['type'] if 'value' not in msg: raise InvalidMessage('The value is missing') if isinstance(msg['value'], list): if len(msg['value']) != 1: raise InvalidMessage('Value is multivalued: %s' % msg['value']) msg_value = msg['value'][0] else: msg_value = msg['value'] if msg_type not in list(self.types.keys()): raise UnknownMessageType("Type '%s' is unknown" % msg_type) if msg_type not in self.allowed: raise UnallowedMessage("Message type '%s' not allowed" % ( msg_type,)) handler = self.types[msg_type](request) handler.parse(msg_value, name) return handler custodia-0.5.0/src/custodia/message/kem.py000066400000000000000000000204601310463436300205100ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import import os import time from jwcrypto.common import json_decode from jwcrypto.common import json_encode from jwcrypto.jwe import JWE from jwcrypto.jwk import JWK from jwcrypto.jws import JWS from jwcrypto.jwt import JWT from custodia.httpd.authorizers import SimplePathAuthz from custodia.log import getLogger from custodia.message.common import InvalidMessage from custodia.message.common import MessageHandler logger = getLogger(__name__) KEY_USAGE_SIG = 0 KEY_USAGE_ENC = 1 KEY_USAGE_MAP = {KEY_USAGE_SIG: 'sig', KEY_USAGE_ENC: 'enc'} class UnknownPublicKey(Exception): def __init__(self, message=None): logger.debug(message) super(UnknownPublicKey, self).__init__(message) class KEMKeysStore(SimplePathAuthz): """A KEM Keys Store. This is a store that holds public keys of registered clients allowed to use KEM messages. It takes the form of an authorizer merely for the purpose of attaching itself to a 'request' so that later on the KEM Parser can fetch the appropriate key to verify/decrypt an incoming request and make the payload available. The KEM Parser will actually perform additional authorization checks in this case. SimplePathAuthz is extended here as we ant to attach the store only to requests on paths we are configured to manage. """ def __init__(self, config): super(KEMKeysStore, self).__init__(config) self._server_keys = None self._alg = None self._enc = None def _db_key(self, kid): return os.path.join('kemkeys', kid) def handle(self, request): inpath = super(KEMKeysStore, self).handle(request) if inpath: request['KEMKeysStore'] = self return inpath def find_key(self, kid, usage): dbkey = self._db_key('%s/%s' % (KEY_USAGE_MAP[usage], kid)) pubkey = self.store.get(dbkey) if pubkey is None: raise UnknownPublicKey(kid) return pubkey @property def server_keys(self): if self._server_keys is None: if 'server_keys' not in self.config: raise UnknownPublicKey("Server Keys not defined") skey = self.find_key(self.config['server_keys'], KEY_USAGE_SIG) ekey = self.find_key(self.config['server_keys'], KEY_USAGE_ENC) self._server_keys = [JWK(**(json_decode(skey))), JWK(**(json_decode(ekey)))] return self._server_keys @property def alg(self): if self._alg is None: alg = self.config.get('signing_algorithm', None) if alg is None: ktype = self.server_keys[KEY_USAGE_SIG].key_type if ktype == 'RSA': alg = 'RS256' elif ktype == 'EC': alg = 'ES256' else: raise ValueError('Key type unsupported for signing') self._alg = alg return self._alg def check_kem_claims(claims, name): if 'sub' not in claims: raise InvalidMessage('Missing subject in payload') if claims['sub'] != name: raise InvalidMessage('Key name %s does not match subject %s' % ( name, claims['sub'])) if 'exp' not in claims: raise InvalidMessage('Missing expiration time in payload') if claims['exp'] - (10 * 60) > int(time.time()): raise InvalidMessage('Message expiration too far in the future') if claims['exp'] < int(time.time()): raise InvalidMessage('Message Expired') class KEMHandler(MessageHandler): """Handles 'kem' messages""" def __init__(self, request): super(KEMHandler, self).__init__(request) self.kkstore = self.req.get('KEMKeysStore', None) if self.kkstore is None: raise Exception('KEM KeyStore not configured') self.client_keys = None self.name = None def _get_key(self, header, usage): if 'kid' not in header: raise InvalidMessage("Missing key identifier") key = self.kkstore.find_key(header['kid'], usage) if key is None: raise UnknownPublicKey('Key found [kid:%s]' % header['kid']) return json_decode(key) def parse(self, msg, name): """Parses the message. We check that the message is properly formatted. :param msg: a json-encoded value containing a JWS or JWE+JWS token :raises InvalidMessage: if the message cannot be parsed or validated :returns: A verified payload """ try: jtok = JWT(jwt=msg) except Exception as e: raise InvalidMessage('Failed to parse message: %s' % str(e)) try: token = jtok.token if isinstance(token, JWE): token.decrypt(self.kkstore.server_keys[KEY_USAGE_ENC]) # If an encrypted payload is received then there must be # a nested signed payload to verify the provenance. payload = token.payload.decode('utf-8') token = JWS() token.deserialize(payload) elif isinstance(token, JWS): pass else: raise TypeError("Invalid Token type: %s" % type(jtok)) # Retrieve client keys for later use self.client_keys = [ JWK(**self._get_key(token.jose_header, KEY_USAGE_SIG)), JWK(**self._get_key(token.jose_header, KEY_USAGE_ENC))] # verify token and get payload token.verify(self.client_keys[KEY_USAGE_SIG]) claims = json_decode(token.payload) except Exception as e: logger.debug('Failed to validate message', exc_info=True) raise InvalidMessage('Failed to validate message: %s' % str(e)) check_kem_claims(claims, name) self.name = name self.payload = claims.get('value') self.msg_type = 'kem' return {'type': self.msg_type, 'value': {'kid': self.client_keys[KEY_USAGE_ENC].key_id, 'claims': claims}} def reply(self, output): if self.client_keys is None: raise UnknownPublicKey("Peer key not defined") ktype = self.client_keys[KEY_USAGE_ENC].key_type if ktype == 'RSA': enc = ('RSA-OAEP', 'A256CBC-HS512') else: raise ValueError("'%s' type not supported yet" % ktype) value = make_enc_kem(self.name, output, self.kkstore.server_keys[KEY_USAGE_SIG], self.kkstore.alg, self.client_keys[1], enc) return {'type': 'kem', 'value': value} class KEMClient(object): def __init__(self, server_keys, client_keys): self.server_keys = server_keys self.client_keys = client_keys def make_request(self, name, value=None, alg="RS256", encalg=None): if encalg is None: return make_sig_kem(name, value, self.client_keys[KEY_USAGE_SIG], alg) else: return make_enc_kem(name, value, self.client_keys[KEY_USAGE_SIG], alg, self.server_keys[KEY_USAGE_ENC], encalg) def parse_reply(self, name, message): claims = decode_enc_kem(message, self.client_keys[KEY_USAGE_ENC], self.server_keys[KEY_USAGE_SIG]) check_kem_claims(claims, name) return claims['value'] def make_sig_kem(name, value, key, alg): header = {'kid': key.key_id, 'alg': alg} claims = {'sub': name, 'exp': int(time.time() + (5 * 60))} if value is not None: claims['value'] = value jwt = JWT(header, claims) jwt.make_signed_token(key) return jwt.serialize(compact=True) def make_enc_kem(name, value, sig_key, alg, enc_key, enc): plaintext = make_sig_kem(name, value, sig_key, alg) eprot = {'kid': enc_key.key_id, 'alg': enc[0], 'enc': enc[1]} jwe = JWE(plaintext, json_encode(eprot)) jwe.add_recipient(enc_key) return jwe.serialize(compact=True) def decode_enc_kem(message, enc_key, sig_key): jwe = JWT(jwt=message, key=enc_key) jws = JWT(jwt=jwe.claims, key=sig_key) return json_decode(jws.claims) custodia-0.5.0/src/custodia/message/simple.py000066400000000000000000000022741310463436300212300ustar00rootroot00000000000000# Copyright (C) 2015 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import from six import string_types from custodia.message.common import InvalidMessage from custodia.message.common import MessageHandler class SimpleKey(MessageHandler): """Handles 'simple' messages""" def parse(self, msg, name): """Parses a simple message :param msg: the json-decoded value :param name: the requested name :raises UnknownMessageType: if the type is not 'simple' :raises InvalidMessage: if the message cannot be parsed or validated """ # On requests we imply 'simple' if there is no input message if msg is None: return if not isinstance(msg, string_types): raise InvalidMessage("The 'value' attribute is not a string") self.name = name self.payload = msg self.msg_type = 'simple' def reply(self, output): if output is None: return None if self.name.endswith('/'): # directory listings are pass-through with simple messages return output return {'type': self.msg_type, 'value': output} custodia-0.5.0/src/custodia/plugin.py000066400000000000000000000337171310463436300176170ustar00rootroot00000000000000# Copyright (C) 2016 Custodia Project Contributors - see LICENSE file from __future__ import absolute_import import abc import grp import inspect import json import pwd import re import sys from jwcrypto.common import json_encode import six from .compat import configparser from .log import CustodiaLoggingAdapter, auditlog, getLogger logger = getLogger(__name__) class _Required(object): __slots__ = () def __repr__(self): return 'REQUIRED' class INHERIT_GLOBAL(object): # noqa: N801 __slots__ = ('default',) def __init__(self, default): self.default = default def __repr__(self): return 'INHERIT_GLOBAL({})'.format(self.default) REQUIRED = _Required() class CustodiaException(Exception): pass class HTTPError(CustodiaException): def __init__(self, code=None, message=None): self.code = code if code is not None else 500 self.mesg = message errstring = '%d: %s' % (self.code, self.mesg) super(HTTPError, self).__init__(errstring) class CSStoreError(CustodiaException): pass class CSStoreExists(CustodiaException): pass class CSStoreUnsupported(CustodiaException): pass class CSStoreDenied(CustodiaException): pass class OptionHandler(object): """Handler and parser for plugin options """ def __init__(self, parser, section): self.parser = parser self.section = section # handler is reserved to look up the plugin class self.seen = {'handler'} def get(self, po): """Lookup value for a PluginOption instance Args: po: PluginOption Returns: converted value """ name = po.name typ = po.typ default = po.default handler = getattr(self, '_get_{}'.format(typ), None) if handler is None: raise ValueError(typ) self.seen.add(name) # pylint: disable=not-callable if not self.parser.has_option(self.section, name): if default is REQUIRED: raise NameError(self.section, name) if isinstance(default, INHERIT_GLOBAL): return handler('global', name, default.default) # don't return default here, give the handler a chance to modify # the default, e.g. pw_uid with default='root' returns 0. return handler(self.section, name, default) # pylint: enable=not-callable def check_surplus(self): surplus = [] for name, _ in self.parser.items(self.section): if (name not in self.seen and not self.parser.has_option(configparser.DEFAULTSECT, name)): surplus.append(name) return surplus def _get_int(self, section, name, default): return self.parser.getint(section, name, fallback=default) def _get_oct(self, section, name, default): value = self.parser.get(section, name, fallback=default) return int(value, 8) def _get_hex(self, section, name, default): value = self.parser.get(section, name, fallback=default) return int(value, 16) def _get_float(self, section, name, default): return self.parser.getfloat(section, name, fallback=default) def _get_bool(self, section, name, default): return self.parser.getboolean(section, name, fallback=default) def _get_regex(self, section, name, default): value = self.parser.get(section, name, fallback=default) if not value: return None else: return re.compile(value) def _get_str(self, section, name, default): return self.parser.get(section, name, fallback=default) def _get_str_set(self, section, name, default): try: value = self.parser.get(section, name) except configparser.NoOptionError: return default if not value or not value.strip(): return None else: return set(v.strip() for v in value.split(' ')) def _get_str_list(self, section, name, default): try: value = self.parser.get(section, name) except configparser.NoOptionError: return default if not value or not value.strip(): return None else: return list(v.strip() for v in value.split(' ') if v.strip()) def _get_store(self, section, name, default): return self.parser.get(section, name, fallback=default) def _get_pwd_uid(self, section, name, default): value = self.parser.get(section, name, fallback=default) try: return int(value) except ValueError: return pwd.getpwnam(value).pw_uid def _get_grp_gid(self, section, name, default): value = self.parser.get(section, name, fallback=default) try: return int(value) except ValueError: return grp.getgrnam(value).gr_gid def _get_json(self, section, name, default): value = self.parser.get(section, name, fallback=default) return json.loads(value) class PluginOption(object): """Plugin option code:: class MyPlugin(CustodiaPlugin): number = PluginOption(int, REQUIRED, 'my value') values = PluginOption('str_list', 'foo bar', 'a list of strings') config:: [myplugin] handler = MyPlugin number = 1 values = egg spam python **Supported value types** *str* plain string *str_set* set of space-separated strings *str_list* ordered list of space-separated strings *int* number (converted from base 10) *hex* number (converted from base 16) *oct* number (converted from base 8) *float* floating point number *bool* boolean (true: on, true, yes, 1; false: off, false, no, 0) *regex* regular expression string *store* special value for refer to a store plugin *pwd_uid* numeric user id or user name *grp_gid* numeric group id or group name *json* JSON string """ __slots__ = ('name', 'typ', 'default', 'doc') def __init__(self, typ, default, doc): self.name = None if typ in {str, int, float, bool, oct, hex}: self.typ = typ.__name__ else: self.typ = typ self.default = default self.doc = doc def __repr__(self): if self.default is REQUIRED: msg = "" else: msg = ("