├── .gitignore ├── .gitlab-ci.yml ├── CHANGES.txt ├── Dockerfile.tools ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── caramel ├── __init__.py ├── config.py ├── models.py ├── scripts │ ├── __init__.py │ ├── autosign.py │ ├── generate_ca.py │ ├── initializedb.py │ └── tool.py ├── static │ ├── favicon.ico │ ├── footerbg.png │ ├── headerbg.png │ ├── ie6.css │ ├── middlebg.png │ ├── pylons.css │ ├── pyramid-small.png │ ├── pyramid.png │ └── transparent.gif ├── templates │ └── mytemplate.pt └── views.py ├── development.ini ├── doc ├── TODO.txt ├── caramel-ER.dia ├── deployment_notes.txt ├── misc_reading.txt └── other_projects.txt ├── fcgi-utils ├── caramel.wsgi ├── paste-launcher.py └── paste-launcher.sh ├── minimal.ini ├── pre-commit-checks ├── production.ini ├── request-certificate ├── caramelrequest │ ├── __init__.py │ └── certificaterequest.py ├── request-cert └── setup.py ├── scripts ├── caramel-deploy.sh ├── caramel-refresh.conf ├── caramel-refresh.sh ├── caramel_launcher.ini ├── caramel_launcher.sh ├── client-example.sh └── post-deploy.sh ├── setup.cfg ├── setup.py └── tests ├── __init__.py ├── ca_test_input.txt ├── fixtures.py ├── test_config.py ├── test_models.py └── test_views.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg 2 | *.egg-info 3 | *.py[co] 4 | *.pt.py 5 | *.txt.py 6 | *~ 7 | .*.swp 8 | *.sqlite 9 | .coverage* 10 | __pycache__ 11 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # Keep the includes first to illustrate that definitions that everything that 3 | # follows override included definitions. 4 | include: 5 | # https://docs.gitlab.com/ee/ci/yaml/README.html#includefile 6 | - project: ModioAB/CI 7 | ref: main 8 | file: 9 | - /ci/default.yml 10 | - /ci/rebase.yml 11 | 12 | workflow: 13 | # Similar to "MergeRequest-Pipelines" default template. 14 | # Adds extra "EXTERNAL_PULL_REQUEST_IID" 15 | # see: https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Workflows/MergeRequest-Pipelines.gitlab-ci.yml 16 | rules: 17 | - if: $CI_MERGE_REQUEST_IID 18 | - if: $CI_EXTERNAL_PULL_REQUEST_IID 19 | - if: $CI_COMMIT_TAG 20 | - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH 21 | - if: $CI_COMMIT_BRANCH 22 | 23 | 24 | stages: 25 | - test 26 | - rebase 27 | 28 | caramel:test: 29 | stage: test 30 | image: ${PYTHON_IMAGE} 31 | before_script: 32 | - python3 -m pip install . 33 | script: 34 | - python3 -m unittest discover 35 | 36 | caramel:test:deprecation: 37 | extends: caramel:test 38 | allow_failure: true 39 | script: 40 | - python3 -W error::DeprecationWarning -m unittest discover 41 | 42 | caramel:systest: 43 | stage: test 44 | image: ${BUILD_IMAGE} 45 | before_script: 46 | - python3 -m pip install . 47 | - dnf -y install openssl 48 | - test -e /etc/machine-id || echo f26871a049f84136bb011f4744cde2dd > /etc/machine-id 49 | script: 50 | - make systest 51 | 52 | rebase:test: 53 | extends: .rebase 54 | stage: rebase 55 | needs: 56 | - caramel:test 57 | script: 58 | - python3 -m pip install . 59 | - git every 60 | -x 'python3 -m pip install --editable .' 61 | -x 'flake8 caramel/ tests/' 62 | -x 'black --check caramel/ tests/' 63 | 64 | caramel:black: 65 | stage: test 66 | image: ${PYTHON_IMAGE} 67 | before_script: 68 | - python3 -m pip install black 69 | script: 70 | - black --check --diff caramel/ tests/ 71 | 72 | caramel:flake: 73 | stage: test 74 | image: ${PYTHON_IMAGE} 75 | before_script: 76 | - python3 -m pip install flake8 77 | script: 78 | - flake8 caramel/ tests/ 79 | 80 | caramel:mypy: 81 | stage: test 82 | when: always 83 | image: ${PYTHON_IMAGE} 84 | before_script: 85 | - python3 -m pip install mypy "sqlalchemy[mypy]<2" 86 | script: 87 | - mypy --install-types --non-interactive --config-file=setup.cfg caramel/ tests/ 88 | 89 | caramel:pylint: 90 | stage: test 91 | when: always 92 | image: ${PYTHON_IMAGE} 93 | before_script: 94 | - python3 -m pip install pylint pylint-exit 95 | - python3 setup.py develop 96 | script: 97 | - pylint --rcfile=setup.cfg caramel/ tests/ || pylint-exit --error-fail $? 98 | 99 | rebase:check: 100 | extends: .rebase 101 | stage: rebase 102 | needs: 103 | - caramel:flake 104 | - caramel:black 105 | script: 106 | - python3 -m pip install black flake8 107 | # Always install "." first to track possible dependency changes 108 | - git every 109 | -x 'python3 -m pip install --editable .' 110 | -x 'flake8 caramel/ tests/' 111 | -x 'black --check caramel/ tests/' 112 | -------------------------------------------------------------------------------- /CHANGES.txt: -------------------------------------------------------------------------------- 1 | 1.7 2 | --- 3 | 4 | - Change data model from pem being Text to pem being Binary. There are no 5 | automatic Migrations, so either dump & restore or revamp. 6 | 7 | 1.6 8 | --- 9 | 10 | - Adding root ca to public api 11 | - Adding bundle ca to public api (not quite present) 12 | 13 | 1.4 14 | --- 15 | 16 | - Autosign daemon 17 | - subjectAltName extension added to signed certs 18 | - refresh improvements 19 | 20 | 1.0 21 | --- 22 | 23 | - Capable of running in production for both servers & embedded clients 24 | - Matches the CA cert for "enforced" Subject lines, and adds the appropriate 25 | X509 extensions to certificates. 26 | 27 | 28 | 0.0 29 | --- 30 | 31 | - Initial version 32 | -------------------------------------------------------------------------------- /Dockerfile.tools: -------------------------------------------------------------------------------- 1 | FROM python:3.9-slim-buster as build 2 | COPY [".", "/build"] 3 | WORKDIR /wheel 4 | RUN pip3 install wheel 5 | RUN pip3 wheel --wheel-dir=/wheel /build 6 | 7 | FROM python:3.9-slim-buster as install 8 | COPY --from=build ["/wheel", "/wheel"] 9 | ENV CARAMEL_INI="/etc/caramel/caramel.ini" 10 | COPY ["minimal.ini", "${CARAMEL_INI}"] 11 | RUN pip3 install --no-index --find-links=/wheel caramel 12 | RUN rm -rf /wheel 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.txt *.ini *.cfg *.rst 2 | recursive-include caramel *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.mako *.js *.html *.xml 3 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | #Python3 and virtual environment 2 | VENV := $(shell mktemp -d /tmp/caramel-test.XXXXX) 3 | PYTHON3 := $(VENV)/bin/python3 4 | 5 | # PIDs of background processes saved at VENV/[PROGRAM]-[test].pid 6 | SERVER := $(VENV)/server 7 | AUTOSIGN := $(VENV)/autosign 8 | 9 | # Database and CA cert and key for caramel server to use 10 | DB_FILE := $(VENV)/caramel.sqlite 11 | DB_URL := sqlite:///$(DB_FILE) 12 | CA_CERT := $(VENV)/example_ca/caramel.ca.cert 13 | CA_KEY := $(VENV)/example_ca/caramel.ca.key 14 | 15 | # client.crt will be generated if the server correctly gives our stored CSR back 16 | CLIENT_CERT := $(VENV)/client.crt 17 | 18 | # If caramel_tool exists in the venv caramel has been installed 19 | CARAMEL_TOOL := $(VENV)/bin/caramel_tool 20 | 21 | # Terminal formatting 22 | BOLD := printf "\033[1m" 23 | PASS := $(BOLD); printf "\033[32m" 24 | FAIL := $(BOLD); printf "\033[31m" 25 | LINE := $(BOLD); echo "---------------------------------------" 26 | RESET_TERM := printf "\033[0m" 27 | BLR := $(BOLD); $(LINE); $(RESET_TERM) #Bold Line, Reset formatting 28 | 29 | # Make sure we dont use any exsisting env vars 30 | unexport CARAMEL_INI CARAMEL_CA_CERT CARAMEL_CA_KEY CARAMEL_DBURL CARAMEL_HOST CARAMEL_PORT CARAMEL_LOG_LEVEL 31 | 32 | #Check for python3 install and virtual environment 33 | $(PYTHON3): 34 | @if [ -z python3 ]; then \ 35 | $(FAIL);\ 36 | echo "Python 3 could not be found.";\ 37 | $(RESET_TERM);\ 38 | exit 2; \ 39 | fi 40 | @$(BOLD); echo "Create a new venv for testing at $(VENV)";\ 41 | $(BLR); 42 | python3 -m venv $(VENV) 43 | @$(BLR) 44 | 45 | 46 | #Install the project via setup.py 47 | .PHONY: venv-install 48 | venv-install: $(CARAMEL_TOOL) 49 | $(CARAMEL_TOOL): $(PYTHON3) setup.py 50 | @$(BOLD); echo "Install caramel and its dependencies in venv: $(VENV)";\ 51 | $(BLR); 52 | $(VENV)/bin/python3 -m pip install -e . 53 | cp development.ini $(VENV)/development.ini 54 | mkdir $(VENV)/example_ca 55 | @$(BLR) 56 | 57 | # Create a sqlite-db configured for use with caramel 58 | .PHONY: gen-db% 59 | gen-db%: $(CARAMEL_TOOL) 60 | @$(BOLD); echo "Create a new DB at $(DB_FILE)";\ 61 | $(BLR); 62 | $(VENV)/bin/caramel_initialize_db $(CARAMEL_COMMAND_LINE) 63 | @$(BLR) 64 | 65 | # Generate a new CA cert and key pair 66 | .PHONY: ca-cert% 67 | ca-cert%: $(CARAMEL_TOOL) 68 | @$(BOLD); echo "Generate new CA cert and key with tests/ca_test_input.txt";\ 69 | $(BLR) 70 | $(VENV)/bin/caramel_ca $(CARAMEL_COMMAND_LINE) < tests/ca_test_input.txt 71 | @$(BLR) 72 | 73 | # Start caramel using pserve in the background, save PID to SERVER 74 | $(SERVER)-env.pid: ca-cert-env gen-db-env 75 | @ $(BOLD); echo "Start new caramel server in the background, sleep 2s to \ 76 | give it time to start";\ 77 | $(BLR) 78 | chmod +x scripts/caramel_launcher.sh 79 | setsid ./scripts/caramel_launcher.sh $(VENV)/bin/pserve >/dev/null 2>&1 < /dev/null & \ 80 | echo $$! > $(SERVER)-env.pid 81 | sleep 2s 82 | @$(BLR) 83 | 84 | 85 | # Start caramel using pserve in the background, save PID to SERVER 86 | $(SERVER)-in%.pid: ca-cert-in% gen-db-in% 87 | @ $(BOLD); echo "Start new caramel server in the background, sleep 2s to \ 88 | give it time to start";\ 89 | $(BLR) 90 | setsid $(VENV)/bin/pserve $(CARAMEL_COMMAND_LINE) >/dev/null 2>&1 < /dev/null & \ 91 | echo $$! > $(SERVER)-in$*.pid 92 | sleep 2s 93 | @$(BLR) 94 | 95 | # Start caramel_autosign in the background, save PID to ENV_AUTOSIGN 96 | $(AUTOSIGN)%.pid: $(CARAMEL_TOOL) ca-cert% gen-db% 97 | @$(BOLD);echo "Start new caramel_autosign in the background";\ 98 | $(BLR) 99 | setsid $(VENV)/bin/caramel_autosign $(CARAMEL_COMMAND_LINE) >/dev/null 2>&1 < /dev/null &\ 100 | echo $$! > $(AUTOSIGN)$*.pid 101 | @$(BLR) 102 | 103 | # Try to upload a CSR to a caramel server and then confirm our CSR was stored 104 | .PHONY: client-run% 105 | client-run%: $(SERVER)%.pid $(AUTOSIGN)%.pid 106 | @ $(BOLD); echo "Use client-example.sh to upload our CSR, wait for it to \ 107 | get processed, then call it again to confirm the server stored our CSR";\ 108 | $(BLR) 109 | chmod +x scripts/client-example.sh 110 | ./scripts/client-example.sh $(VENV) 111 | sleep 2s 112 | ./scripts/client-example.sh $(VENV) 113 | @$(BLR) 114 | 115 | 116 | # Basic tests that caramel can be installed and run with test data, 117 | .PHONY: systest% 118 | systest: systest-env systest-ini systest-ini-env systest-ini-commandline 119 | @ $(PASS); $(LINE);\ 120 | echo "Systest passed"; \ 121 | $(BLR) 122 | 123 | # using environment variables for config 124 | systest-env: export CARAMEL_COMMAND_LINE = 125 | systest-env: export CARAMEL_DBURL = $(DB_URL) 126 | systest-env: export CARAMEL_CA_CERT = $(CA_CERT) 127 | systest-env: export CARAMEL_CA_KEY = $(CA_KEY) 128 | systest-env: export CARAMEL_HOST = 127.0.0.1 129 | systest-env: export CARAMEL_PORT = 6543 130 | systest-env: export CARAMEL_LOG_LEVEL = ERROR 131 | 132 | # using only .ini-file for config on the command line 133 | systest-ini: export CARAMEL_COMMAND_LINE = $(VENV)/development.ini 134 | 135 | # using only .ini-file for config for server, rest ini from env 136 | systest-ini-env: export CARAMEL_INI = $(VENV)/development.ini 137 | $(SERVER)-ini-env.pid: export CARAMEL_COMMAND_LINE = $(VENV)/development.ini 138 | $(AUTOSIGN)-db-ini-env.pid: export CARAMEL_COMMAND_LINE = 139 | ca-cert-ini-env: export CARAMEL_COMMAND_LINE = 140 | gen-db-ini-env: export CARAMEL_COMMAND_LINE = 141 | 142 | # using only .ini-file for config for server, rest commandline 143 | $(SERVER)-ini-commandline.pid: export CARAMEL_COMMAND_LINE = $(VENV)/development.ini 144 | $(AUTOSIGN)-ini-commandline.pid: export CARAMEL_COMMAND_LINE = --dburl=$(DB_URL) --ca-cert="$(CA_CERT)" --ca-key="$(CA_KEY)" 145 | ca-cert-ini-commandline: export CARAMEL_COMMAND_LINE = --ca-cert="$(CA_CERT)" --ca-key="$(CA_KEY)" 146 | gen-db-ini-commandline: export CARAMEL_COMMAND_LINE = --dburl $(DB_URL) 147 | 148 | systest-%: client-run-% 149 | @kill $(shell cat $(SERVER)-$*.pid);\ 150 | if [ $$? -eq 0 ]; then \ 151 | $(PASS); $(LINE);\ 152 | echo "Caramel server started and terminated successfully";\ 153 | else \ 154 | $(FAIL); $(LINE);\ 155 | echo "$@ failed: Caramel server exited before termination with\ 156 | exit code: $$?";\ 157 | exit 1;\ 158 | fi; 159 | @$(BLR) 160 | 161 | @kill $(shell cat $(AUTOSIGN)-$*.pid);\ 162 | if [ $$? -eq 0 ]; then \ 163 | $(PASS); $(LINE);\ 164 | echo "Autosign server started and terminated successfully";\ 165 | else \ 166 | $(FAIL); $(LINE);\ 167 | echo "$@ failed: Autosign server exited before terminated with\ 168 | exit code: $$?";\ 169 | exit 1;\ 170 | fi; 171 | @$(BLR) 172 | 173 | @if [ -f $(CLIENT_CERT) ]; then \ 174 | $(PASS); $(LINE);\ 175 | echo "$@ passed: Caramel successfully registered our CSR";\ 176 | else \ 177 | $(FAIL); $(LINE);\ 178 | echo "$@ failed: Something went wrong when communicating with \ 179 | the server";\ 180 | exit 1;\ 181 | fi;\ 182 | $(BLR) 183 | @ echo "Move test data after successfull run" 184 | mkdir $(VENV)/$@ 185 | mv -t $(VENV)/$@ $(CLIENT_CERT) $(DB_FILE) $(CA_CERT) $(CA_KEY) 186 | 187 | 188 | # Removes the virtual environment created via this makefile, 189 | # NOTE: this will remove all previous virtual environments 190 | .PHONY: clean 191 | clean: 192 | @echo "Removing local test virtual environment"; $(BLR) 193 | rm -rf $(VENV) 194 | @$(BLR) 195 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Caramel README 2 | ============== 3 | 4 | What is Caramel? 5 | ---------------- 6 | 7 | Caramel is a certificate management system that makes it easy to use 8 | client certificates in web applications, mobile applications, embedded use 9 | and other places. It solves the certificate signing and certificate 10 | management headache, while attempting to be easy to deploy, maintain and 11 | use in a secure manner. 12 | 13 | Caramel makes it easier (it's never completely easy) to run your own 14 | certificate authority and manage and maintain keys and signing periods. 15 | 16 | Caramel focuses on reliably and continuously updating short-lived certificates 17 | where clients (and embedded devices) continue to "phone home" and fetch 18 | updated certificates. This means that we do not have to provide OCSP and CRL 19 | endpoints to handle compromised certificates, but only have to stop updating 20 | the certificate. This also means that expired certificates should be 21 | considered broken. 22 | 23 | 24 | How does Caramel work? 25 | ---------------------- 26 | 27 | Caramel is a REST-ful web application that accepts certificate signing 28 | requests (CSR) from anyone, stores them, and possibly returns a signed 29 | certificate. 30 | 31 | A client pushes its certificate signing request (CSR) to the public web 32 | application. The web application validates the CSR, and stores it in a 33 | database. 34 | 35 | A backend (administration) web application talks to the same database 36 | (preferably from inside an intranet or other secure place), and lets you 37 | view signing requests, and sign them. 38 | 39 | The certificates are signed with a *short* lifetime (3 days), and client 40 | scripts are supposed to regularly contact the public web service and 41 | download a freshly signed certificate. Root (Certificate Authority) keys 42 | only live on the "administration" part, and should preferably be kept on a 43 | non-public machine. 44 | 45 | 46 | What should I take special care about? 47 | -------------------------------------- 48 | 49 | *No* identity validation is performed by the application, this is left as 50 | an exercise for the reader. 51 | 52 | Your signing keys are stored on the administration machine. 53 | 54 | If a client doesn't regularly download its public certificate, it will 55 | time out and become "stale", thus preventing future connections. 56 | 57 | 58 | Example usage 59 | ------------- 60 | 61 | We install the administration interface and database on an internal 62 | machine (intranet) and put the public application on our software update 63 | service. We use the unique identifier for each client (its machine-ID or 64 | mac-address) as the identifier, and manually match these when initially 65 | signing requests. 66 | 67 | Since the CSR doesn't change with time, it is re-signed every 15 days, and 68 | in the client startup sequence, the client will download a refreshed 69 | certificate from the caramel server. 70 | 71 | Example implementation of a client (in shell-script, using OpenSSL) is 72 | included. The example includes: 73 | 74 | - Generating a key 75 | - Generating a signing request 76 | - Uploading a signing request 77 | - Fetching a valid certificate 78 | - Updating a valid certificate 79 | 80 | 81 | Security trade-offs 82 | ------------------- 83 | 84 | We have made a conscious decision to have signing keys living 85 | (unencrypted, for now) on the administration server. This is a usability 86 | trade-off in order to make it possible to smoothly use signing keys. 87 | 88 | We set strict limits on what kinds of crypto, strings and other things are 89 | allowed in a CSR. 90 | 91 | We are doing our very best to **not** build crypto. OpenSSL is used 92 | wherever possible, and we try to **not** implement our own algorithms for 93 | fear of doing it wrongly. 94 | 95 | 96 | Maintaining your certificates 97 | ----------------------------- 98 | 99 | In a server environment with several certificates you usually end up 100 | rotating/refreshing them in a cron job. 101 | Included under scripts/ is a tool called `caramel-refresh.sh` that will parse a 102 | config file, and automatically refresh all certificates matching. This requires 103 | the original CSR and certificate to be in place. See `request-certificate` for a 104 | tool to generate your own certificates. 105 | 106 | `caramel-refresh` is intended to be run in a cron job on servers (or clients). 107 | Please make sure you run the job as the correct user, so permissions aren't a 108 | problem afterwards. 109 | 110 | 111 | Getting Started 112 | --------------- 113 | ``` 114 | cd 115 | $venv/bin/python setup.py develop 116 | $venv/bin/caramel_initialize_db development.ini 117 | $venv/bin/caramel_ca development.ini 118 | $venv/bin/pserve development.ini 119 | ``` 120 | 121 | Running Tests 122 | ------------- 123 | ``` 124 | cd 125 | $venv/bin/python setup.py develop 126 | $venv/bin/python -m unittest discover 127 | ``` 128 | 129 | 130 | Running Tests with Nose 131 | ----------------------- 132 | 133 | ``` 134 | cd 135 | $venv/bin/python setup.py develop 136 | $venv/bin/pip install nose 137 | nosetests 138 | ``` 139 | 140 | 141 | Installing the Commit Hook 142 | -------------------------- 143 | 144 | We use commit-hooks to run test-cases in a clean virtualenv before each commit. 145 | This is to ensure a certain level of quality and code standards, and to prevent 146 | missing dependencies in setup.py. Running these tests at each commit can be 147 | expensive as it involves going to the network and downloading every package 148 | from scratch. This is not a concern for our development environment, but may be 149 | a problem for others. 150 | 151 | 152 | Install the hooks with the following commands: 153 | ``` 154 | cd 155 | ln -rs pre-commit-checks .git/hooks/pre-commit 156 | ``` 157 | 158 | Please note the "-r" flag to ln, as it makes sure the relative link keeps the 159 | correct path. 160 | 161 | For the pre-commit hook to work, you need to have flake8 available. Either 162 | install flake8 via: 163 | 164 | `pip install flake8` 165 | 166 | Or point git config hooks.flake8 to the flake8 executable: 167 | 168 | `git config hooks.flake8 /path/to/flake8` 169 | 170 | 171 | Dependencies needed from the operating system 172 | --------------------------------------------- 173 | 174 | * libffi-devel (on RHEL/CentOS) 175 | * openssl, openssl-devel 176 | * gcc 177 | 178 | 179 | Making sure you have VirtualEnv 180 | ------------------------------- 181 | 182 | To use the commit hook you need virtualenv available. 183 | If you do not have virtualenv in your path, please point to it with: 184 | 185 | `git config hooks.virtualenv /path/to/virtualenv` 186 | 187 | In order to run the python3 interpreter instead of the normal python2 188 | interpreter, you should configure the hook as this: 189 | 190 | `git config hooks.virtualenv /usr/bin/virtualenv -p /usr/bin/python3` 191 | 192 | 193 | License 194 | ------- 195 | We have chosen the GNU Affero GPL v3 license for the project. We see no need 196 | for others to keep modification to this software a secret, and we welcome 197 | outside providers. Just because the code is GPLv3, doesn't prevent you from 198 | keeping your keys & certificates private. 199 | 200 | For the organizations using this, there should be no additional gain to be 201 | had from keeping the source code secret, and if you think there is any such 202 | gain, please contact us. 203 | -------------------------------------------------------------------------------- /caramel/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | from pyramid.config import Configurator 4 | from sqlalchemy import engine_from_config 5 | 6 | from .config import get_db_url 7 | from .models import ( 8 | init_session, 9 | ) 10 | 11 | 12 | def main(global_config, **settings): 13 | """This function returns a Pyramid WSGI application.""" 14 | settings["sqlalchemy.url"] = get_db_url(settings=settings) 15 | engine = engine_from_config(settings, "sqlalchemy.") 16 | init_session(engine) 17 | config = Configurator(settings=settings) 18 | config.include("pyramid_tm") 19 | config.add_route("ca", "/root.crt", request_method="GET") 20 | config.add_route("cabundle", "/bundle.crt", request_method="GET") 21 | config.add_route("csr", "/{sha256:[0-9a-f]{64}}", request_method="POST") 22 | config.add_route("cert", "/{sha256:[0-9a-f]{64}}", request_method="GET") 23 | config.scan() 24 | return config.make_wsgi_app() 25 | -------------------------------------------------------------------------------- /caramel/config.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | """caramel.config is a helper library that standardizes and collects the logic 4 | in one place used by the caramel CLI tools/scripts""" 5 | 6 | import argparse 7 | import logging 8 | import os 9 | from logging.config import dictConfig 10 | 11 | import pyramid.paster as paster 12 | from pyramid.scripting import prepare 13 | 14 | LOG_LEVEL = { 15 | "ERROR": logging.ERROR, 16 | "WARNING": logging.WARNING, 17 | "INFO": logging.INFO, 18 | "DEBUG": logging.DEBUG, 19 | } 20 | 21 | DEFAULT_LOGGING_CONFIG = { 22 | "version": 1, 23 | "formatters": { 24 | "generic": { 25 | "format": "%(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s]" 26 | "%(message)s" 27 | }, 28 | }, 29 | "handlers": { 30 | "console": { 31 | "class": "logging.StreamHandler", 32 | "stream": "ext://sys.stderr", 33 | "level": "NOTSET", 34 | "formatter": "generic", 35 | }, 36 | }, 37 | "loggers": { 38 | "": { # root logger 39 | "handlers": ["console"], 40 | "level": "INFO", 41 | }, 42 | "caramel": { 43 | "level": "DEBUG", 44 | "qualname": "caramel", 45 | }, 46 | "sqlalchemy": { 47 | "level": "INFO", 48 | "qualname": "sqlalchemy.engine", 49 | }, 50 | }, 51 | } 52 | 53 | DEFAULT_APP_SETTINGS = { 54 | "csrf_trusted_origins": [], 55 | "debug_all": False, 56 | "debug_authorization": False, 57 | "debug_notfound": False, 58 | "debug_routematch": False, 59 | "debug_templates": False, 60 | "default_locale_name": "en", 61 | "prevent_cachebust": False, 62 | "prevent_http_cache": False, 63 | "pyramid.csrf_trusted_origins": [], 64 | "pyramid.debug_all": False, 65 | "pyramid.debug_authorization": False, 66 | "pyramid.debug_notfound": False, 67 | "pyramid.debug_routematch": False, 68 | "pyramid.debug_templates": False, 69 | "pyramid.default_locale_name": "en", 70 | "pyramid.prevent_cachebust": False, 71 | "pyramid.prevent_http_cache": False, 72 | "pyramid.reload_all": False, 73 | "pyramid.reload_assets": False, 74 | "pyramid.reload_resources": False, 75 | "pyramid.reload_templates": True, 76 | "reload_all": False, 77 | "reload_assets": False, 78 | "reload_resources": False, 79 | "reload_templates": True, 80 | } 81 | 82 | 83 | def add_inifile_argument(parser, env=None): 84 | """Adds an argument to the parser for the config-file, defaults to 85 | CARAMEL_INI in the environment""" 86 | if env is None: 87 | env = os.environ 88 | default_ini = env.get("CARAMEL_INI") 89 | 90 | parser.add_argument( 91 | nargs="?", 92 | help="Path to a specific .ini-file to use as config", 93 | dest="inifile", 94 | default=default_ini, 95 | type=str, 96 | ) 97 | 98 | 99 | def add_db_url_argument(parser): 100 | """Adds an argument for the URL for the database to a given parser""" 101 | parser.add_argument( 102 | "--dburl", 103 | help="URL to the database to use", 104 | type=str, 105 | ) 106 | 107 | 108 | def add_verbosity_argument(parser): 109 | """Adds an argument for verbosity to a given parser, counting the amount of 110 | 'v's and 'verbose' on the commandline""" 111 | parser.add_argument( 112 | "-v", 113 | "--verbose", 114 | help="Verbosity of root logger, increasing the more 'v's are added", 115 | action="count", 116 | default=0, 117 | ) 118 | 119 | 120 | def add_ca_arguments(parser): 121 | """Adds a ca-cert and ca-key argument to a given parser""" 122 | parser.add_argument( 123 | "--ca-cert", 124 | help="Path to CA certificate to use", 125 | type=str, 126 | ) 127 | parser.add_argument( 128 | "--ca-key", 129 | help="Path to CA key to use", 130 | type=str, 131 | ) 132 | 133 | 134 | def add_lifetime_arguments(parser): 135 | """Adds an argument for the short and long lifetime of certs""" 136 | parser.add_argument( 137 | "-l", 138 | "--life-short", 139 | help="Lifetime of short term certs", 140 | type=int, 141 | ) 142 | parser.add_argument( 143 | "-s", 144 | "--life-long", 145 | help="Lifetime of long term certs", 146 | type=int, 147 | ) 148 | 149 | 150 | def add_backdate_argument(parser): 151 | """Adds an argument to enable backdating certs""" 152 | parser.add_argument( 153 | "-b", 154 | "--backdate", 155 | help="Use backdating, default is False", 156 | action="store_true", 157 | ) 158 | 159 | 160 | def _get_config_value( 161 | arguments: argparse.Namespace, 162 | variable, 163 | required=False, 164 | setting_name=None, 165 | settings=None, 166 | default=None, 167 | env=None, 168 | ): 169 | """Returns what value to use for a given config variable, prefer argument > 170 | env-variable > config-file, if a value cant be found and default is not 171 | None, default is returned""" 172 | result = None 173 | if setting_name is None: 174 | setting_name = variable 175 | if settings is not None: 176 | result = settings.get(setting_name, result) 177 | 178 | if env is None: 179 | env = os.environ 180 | env_var = "CARAMEL_" + variable.upper().replace("-", "_") 181 | result = env.get(env_var, result) 182 | 183 | arg_value = getattr(arguments, variable, result) 184 | result = arg_value if arg_value is not None else result 185 | 186 | if result is None: 187 | result = default 188 | 189 | if required and result is None: 190 | raise ValueError( 191 | f"No {variable} could be found as either an argument," 192 | f" in the environment variable {env_var} or in the config file", 193 | variable, 194 | env_var, 195 | ) 196 | return result 197 | 198 | 199 | def get_db_url(arguments=None, settings=None, required=True): 200 | """Returns URL to use for database, prefer argument > env-variable > 201 | config-file""" 202 | return _get_config_value( 203 | arguments, 204 | variable="dburl", 205 | required=required, 206 | setting_name="sqlalchemy.url", 207 | settings=settings, 208 | ) 209 | 210 | 211 | def get_log_level(argument_level, logger=None, env=None): 212 | """Calculates the highest verbosity(here inverted) from the argument, 213 | environment and root, capping it to between logging.DEBUG(10)-logging.ERROR(40), 214 | returning the log level""" 215 | 216 | if env is None: 217 | env = os.environ 218 | env_level_name = env.get("CARAMEL_LOG_LEVEL", "ERROR").upper() 219 | env_level = LOG_LEVEL[env_level_name] 220 | 221 | if logger is None: 222 | logger = logging.getLogger() 223 | current_level = logger.level 224 | 225 | argument_verbosity = logging.ERROR - argument_level * 10 # level steps are 10 226 | verbosity = min(argument_verbosity, env_level, current_level) 227 | log_level = ( 228 | verbosity if logging.DEBUG <= verbosity <= logging.ERROR else logging.ERROR 229 | ) 230 | return log_level 231 | 232 | 233 | def configure_log_level(arguments: argparse.Namespace, logger=None): 234 | """Sets the root loggers level to the highest verbosity from the argument, 235 | environment and config-file""" 236 | log_level = get_log_level(arguments.verbose) 237 | if logger is None: 238 | logger = logging.getLogger() 239 | logger.setLevel(log_level) 240 | 241 | 242 | def get_ca_cert_key_path(arguments: argparse.Namespace, settings=None, required=True): 243 | """Returns the path to the ca-cert and ca-key to use""" 244 | ca_cert_path = _get_config_value( 245 | arguments, 246 | variable="ca_cert", 247 | required=required, 248 | setting_name="ca.cert", 249 | settings=settings, 250 | ) 251 | ca_key_path = _get_config_value( 252 | arguments, 253 | variable="ca_key", 254 | required=required, 255 | setting_name="ca.key", 256 | settings=settings, 257 | ) 258 | return ca_cert_path, ca_key_path 259 | 260 | 261 | def get_lifetime_short( 262 | arguments: argparse.Namespace, settings=None, required=False, default=None 263 | ): 264 | """Returns the default lifetime for certs in hours""" 265 | return _get_config_value( 266 | arguments, 267 | variable="life_short", 268 | required=required, 269 | setting_name="lifetime.short", 270 | settings=settings, 271 | default=default, 272 | ) 273 | 274 | 275 | def get_lifetime_long( 276 | arguments: argparse.Namespace, settings=None, required=False, default=None 277 | ): 278 | """Returns the long term certs lifetime in hours""" 279 | return _get_config_value( 280 | arguments, 281 | variable="life_long", 282 | required=required, 283 | setting_name="lifetime.long", 284 | settings=settings, 285 | default=default, 286 | ) 287 | 288 | 289 | def get_backdate( 290 | arguments: argparse.Namespace, settings=None, required=False, default=None 291 | ): 292 | """Returns the long term certs lifetime in hours""" 293 | return _get_config_value( 294 | arguments, 295 | variable="backdate", 296 | required=required, 297 | settings=settings, 298 | default=default, 299 | ) 300 | 301 | 302 | def setup_logging(config_path=None): 303 | """wrapper for pyramid.paster.sertup_logging using file at config.path, if 304 | no config_path is passed on use dictionary DEFAULT_LOGGING_CONFIG""" 305 | if config_path: 306 | paster.setup_logging(config_path) 307 | else: 308 | dictConfig(DEFAULT_LOGGING_CONFIG) 309 | 310 | 311 | def bootstrap(config_path=None, dburl=None): 312 | """wrapper for pyramid.paster.bootstraper, if a config_path is not given 313 | then DEFAULT_APP_SETTINGS to bootstrap the app manually""" 314 | if dburl: 315 | os.environ["CARAMEL_DBURL"] = dburl 316 | if config_path: 317 | return paster.bootstrap(config_path) 318 | else: 319 | from caramel import main as get_app 320 | 321 | app = get_app({}, **DEFAULT_APP_SETTINGS) 322 | env = prepare() 323 | env["app"] = app 324 | return env 325 | 326 | 327 | def get_appsettings(config_path): 328 | """wrapper for pyramid.paster.get_appsettings, if a config_path is not 329 | given then return DEFAULT_APP_SETTINGS""" 330 | if config_path: 331 | return paster.get_appsettings(config_path) 332 | else: 333 | return DEFAULT_APP_SETTINGS 334 | -------------------------------------------------------------------------------- /caramel/models.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | 4 | import datetime as _datetime 5 | import uuid 6 | from typing import List 7 | 8 | import dateutil.parser 9 | import OpenSSL.crypto as _crypto 10 | import sqlalchemy as _sa 11 | import sqlalchemy.orm as _orm 12 | from pyramid.decorator import reify as _reify 13 | from sqlalchemy.ext.declarative import declared_attr 14 | from sqlalchemy.orm import as_declarative 15 | from zope.sqlalchemy import register 16 | 17 | X509_V3 = 0x2 # RFC 2459, 4.1.2.1 18 | 19 | # Bitlength to Hash Strength lookup table. 20 | HASH = {1024: "sha1", 2048: "sha256", 4096: "sha512"} 21 | 22 | # These parts of the subject _must_ match our CA key 23 | CA_SUBJ_MATCH = (b"C", b"ST", b"L", b"O") 24 | 25 | 26 | class SigningCert(object): 27 | """Data class to wrap signing key + cert, to help refactoring""" 28 | 29 | def __init__(self, cert, key=None): 30 | if key: 31 | self.key = _crypto.load_privatekey(_crypto.FILETYPE_PEM, key) 32 | self.cert = _crypto.load_certificate(_crypto.FILETYPE_PEM, cert) 33 | 34 | @classmethod 35 | def from_files(cls, certfile, keyfile=None): 36 | key = None 37 | if keyfile: 38 | with open(keyfile, "rt") as f: 39 | key = f.read() 40 | with open(certfile, "rt") as f: 41 | cert = f.read() 42 | 43 | return cls(cert, key) 44 | 45 | @_reify 46 | def not_before(self): 47 | ts = self.cert.get_notBefore() 48 | if not ts: 49 | return None 50 | return dateutil.parser.parse(ts) 51 | 52 | @_reify 53 | def pem(self): 54 | return _crypto.dump_certificate(_crypto.FILETYPE_PEM, self.cert) 55 | 56 | # Returns the parts we _care_ about in the subject, from a ca 57 | def get_ca_prefix(self, subj_match=CA_SUBJ_MATCH): 58 | subject = self.cert.get_subject() 59 | components = dict(subject.get_components()) 60 | matches = tuple( 61 | (n.decode("utf8"), components[n].decode("utf8")) 62 | for n in subj_match 63 | if n in components 64 | ) 65 | return matches 66 | 67 | 68 | # XXX: probably error prone for cases where things are specified by string 69 | def _fkcolumn(referent, *args, **kwargs): 70 | refcol = referent.property.columns[0] 71 | return _sa.Column(refcol.type, _sa.ForeignKey(referent), *args, **kwargs) 72 | 73 | 74 | DBSession = _orm.scoped_session(_orm.sessionmaker()) 75 | register(DBSession) 76 | 77 | 78 | @as_declarative() 79 | class Base(object): 80 | @declared_attr # type: ignore 81 | def __tablename__(cls) -> str: # pylint: disable=no-self-argument 82 | return cls.__name__.lower() # pylint: disable=no-member 83 | 84 | id = _sa.Column(_sa.Integer, primary_key=True) 85 | 86 | def save(self): 87 | DBSession.add(self) 88 | DBSession.flush() 89 | 90 | @classmethod 91 | def query(cls): 92 | return DBSession.query(cls) 93 | 94 | @classmethod 95 | def all(cls): 96 | return cls.query().all() 97 | 98 | 99 | # XXX: not the best of names 100 | def init_session(engine, create=False): 101 | DBSession.configure(bind=engine) 102 | if create: 103 | Base.metadata.create_all(engine) 104 | else: 105 | Base.metadata.bind = engine 106 | 107 | 108 | # Upper bounds from RFC 5280 109 | _UB_CN_LEN = 64 110 | _UB_OU_LEN = 64 111 | 112 | # Length of hex digest of a sha256 checksum 113 | _SHA256_LEN = 64 114 | 115 | 116 | class CSR(Base): 117 | sha256sum = _sa.Column(_sa.CHAR(_SHA256_LEN), unique=True, nullable=False) 118 | pem = _sa.Column(_sa.LargeBinary, nullable=False) 119 | orgunit = _sa.Column(_sa.String(_UB_OU_LEN)) 120 | commonname = _sa.Column(_sa.String(_UB_CN_LEN)) 121 | rejected = _sa.Column(_sa.Boolean(create_constraint=True)) 122 | accessed: List["AccessLog"] = _orm.relationship( 123 | "AccessLog", 124 | backref="csr", 125 | cascade_backrefs=False, 126 | order_by="AccessLog.when.desc()", 127 | ) 128 | certificates: List["Certificate"] = _orm.relationship( 129 | "Certificate", 130 | backref="csr", 131 | cascade_backrefs=False, 132 | order_by="Certificate.not_after.desc()", 133 | lazy="dynamic", 134 | cascade="all, delete-orphan", 135 | ) 136 | 137 | def __init__(self, sha256sum, reqtext): 138 | # XXX: assert sha256(reqtext).hexdigest() == sha256sum ? 139 | self.sha256sum = sha256sum 140 | self.pem = reqtext 141 | # FIXME: Below 4 lines (try/except) are duped in the req() function. 142 | try: 143 | self.req.verify(self.req.get_pubkey()) 144 | except _crypto.Error: 145 | raise ValueError("invalid PEM reqtext") 146 | # Check for and reject reqtext with trailing content 147 | pem = _crypto.dump_certificate_request(_crypto.FILETYPE_PEM, self.req) 148 | if pem != self.pem: 149 | raise ValueError("invalid PEM reqtext") 150 | self.orgunit = self.subject.OU 151 | self.commonname = self.subject.CN 152 | self.rejected = False 153 | 154 | @_reify 155 | def req(self): 156 | req = _crypto.load_certificate_request(_crypto.FILETYPE_PEM, self.pem) 157 | try: 158 | req.verify(req.get_pubkey()) 159 | except _crypto.Error: 160 | raise ValueError("Invalid Request") 161 | return req 162 | 163 | @_reify 164 | def subject(self): 165 | return self.req.get_subject() 166 | 167 | @_reify 168 | def subject_components(self): 169 | components = self.subject.get_components() 170 | return tuple((n.decode("utf8"), v.decode("utf8")) for n, v in components) 171 | 172 | @classmethod 173 | def valid(cls): 174 | return cls.query().filter_by(rejected=False).all() 175 | 176 | @classmethod 177 | def list_csr_printable(cls): 178 | return ( 179 | DBSession.query( 180 | CSR.id, 181 | CSR.commonname, 182 | CSR.sha256sum, 183 | _sa.func.max(Certificate.not_after), 184 | ) 185 | .outerjoin(CSR.certificates) 186 | .group_by(CSR.id) 187 | .filter(CSR.rejected.is_(False)) 188 | .order_by(CSR.id) 189 | .all() 190 | ) 191 | 192 | @classmethod 193 | def refreshable(cls): 194 | """Using "valid" and looking at csr.certificates doesn't scale. 195 | Better to do it in the Query.""" 196 | 197 | # Options subqueryload is to prevent thousands of small queries and 198 | # instead batch load the certificates at once 199 | all_signed = _sa.select(Certificate.csr_id) 200 | return ( 201 | cls.query().filter_by(rejected=False).filter(CSR.id.in_(all_signed)).all() 202 | ) 203 | 204 | @classmethod 205 | def unsigned(cls): 206 | all_signed = _sa.select(Certificate.csr_id) 207 | return ( 208 | cls.query() 209 | .filter_by(rejected=False) 210 | .filter(CSR.id.notin_(all_signed)) 211 | .all() 212 | ) 213 | 214 | @classmethod 215 | def by_sha256sum(cls, sha256sum): 216 | return cls.query().filter_by(sha256sum=sha256sum).one() 217 | 218 | def __json__(self, request): 219 | url = request.route_url("cert", sha256=self.sha256sum) 220 | return dict(sha256=self.sha256sum, url=url) 221 | 222 | def __str__(self): 223 | return ( 224 | "<{0.__class__.__name__} " # auto-concatenation (no comma) 225 | "sha256sum={0.sha256sum:8.8}... " 226 | "rejected: {0.rejected!r} " 227 | "OU={0.orgunit!r} CN={0.commonname!r}>" 228 | ).format(self) 229 | 230 | def __repr__(self): 231 | return ( 232 | "<{0.__class__.__name__} id={0.id} " # (no comma) 233 | "sha256sum={0.sha256sum}>" 234 | ).format(self) 235 | 236 | 237 | class AccessLog(Base): 238 | # XXX: name could be better 239 | when = _sa.Column(_sa.DateTime, default=_datetime.datetime.utcnow) 240 | # XXX: name could be better, could perhaps be limited length, 241 | # might not want this nullable 242 | addr = _sa.Column(_sa.Text) 243 | csr_id = _fkcolumn(CSR.id, nullable=False) 244 | 245 | def __init__(self, csr, addr): 246 | self.csr = csr 247 | self.addr = addr 248 | 249 | def __str__(self): 250 | return ( 251 | "<{0.__class__.__name__} id={0.id} " "csr={0.csr.sha256sum} when={0.when}>" 252 | ).format(self) 253 | 254 | def __repr__(self): 255 | return "<{0.__class__.__name__} id={0.id}>".format(self) 256 | 257 | 258 | class Extension(object): 259 | """Convenience class to make validating Extensions a bit easier""" 260 | 261 | critical = False 262 | name = None 263 | data = None 264 | text = None 265 | 266 | def __init__(self, ext): 267 | self.name = ext.get_short_name() 268 | self.critical = bool(ext.get_critical()) 269 | self.data = ext.get_data() 270 | self.text = str(ext) 271 | 272 | 273 | class Certificate(Base): 274 | pem = _sa.Column(_sa.LargeBinary, nullable=False) 275 | # XXX: not_after might be enough 276 | not_before = _sa.Column(_sa.DateTime, nullable=False) 277 | not_after = _sa.Column(_sa.DateTime, nullable=False) 278 | csr_id = _fkcolumn(CSR.id, nullable=False) 279 | 280 | def __init__(self, CSR, pem, *args, **kws): 281 | self.pem = pem 282 | self.csr_id = CSR.id 283 | 284 | req = CSR.req 285 | cert_pkey = self.cert.get_pubkey() 286 | 287 | # We can't compare pubkeys directly, so we just verify the signature. 288 | if not req.verify(cert_pkey): 289 | raise ValueError("Public key of cert cannot verify request") 290 | 291 | self.not_before = dateutil.parser.parse(self.cert.get_notBefore()) 292 | self.not_after = dateutil.parser.parse(self.cert.get_notAfter()) 293 | 294 | @_reify 295 | def cert(self): 296 | cert = _crypto.load_certificate(_crypto.FILETYPE_PEM, self.pem) 297 | 298 | extensions = {} 299 | for index in range(0, cert.get_extension_count()): 300 | ext = cert.get_extension(index) 301 | my_ext = Extension(ext) 302 | extensions[my_ext.name] = my_ext 303 | 304 | if cert.get_version() != X509_V3: 305 | raise ValueError("Not a x509.v3 certificate") 306 | 307 | ext = extensions.get(b"basicConstraints") 308 | if not ext: 309 | raise ValueError("Missing Basic Constraints") 310 | 311 | if not ext.critical: 312 | raise ValueError("Extended Key Usage not critical") 313 | 314 | ext = extensions.get(b"extendedKeyUsage") 315 | if not ext: 316 | raise ValueError("Missing Extended Key Usage extension") 317 | if not ext.critical: 318 | raise ValueError("Extended Key Usage not critical") 319 | if "TLS Web Client Authentication" in ext.text: 320 | pass 321 | if "TLS Web Server Authentication" in ext.text: 322 | pass 323 | return cert 324 | 325 | def __repr__(self): 326 | return "<{0.__class__.__name__} id={0.id}>".format(self) 327 | 328 | @classmethod 329 | def sign(cls, CSR, ca, lifetime=_datetime.timedelta(30 * 3), backdate=False): 330 | """Takes a CSR, signs it, generating and returning a Certificate. 331 | backdate causes the CA to set "notBefore" of signed certificates to 332 | match that of the CA Certificate. This is an ugly workaround for a 333 | timekeeping bug in some firmware. 334 | """ 335 | assert isinstance(ca, SigningCert) 336 | notAfter = int(lifetime.total_seconds()) 337 | # TODO: Verify that the data in DB matches csr_add rules in views.py 338 | 339 | cert = _crypto.X509() 340 | cert.set_subject(CSR.req.get_subject()) 341 | cert.set_serial_number(int(uuid.uuid1())) 342 | cert.set_issuer(ca.cert.get_subject()) 343 | cert.set_pubkey(CSR.req.get_pubkey()) 344 | cert.set_version(X509_V3) 345 | cert.gmtime_adj_notBefore(0) 346 | cert.gmtime_adj_notAfter(notAfter) 347 | if backdate and ca.not_before: 348 | now = _datetime.datetime.now(tz=_datetime.timezone.utc) 349 | delta = ca.not_before - now 350 | cert.gmtime_adj_notBefore(int(delta.total_seconds())) 351 | 352 | subjectAltName = bytes("DNS:" + CSR.commonname, "utf-8") 353 | extensions = [ 354 | _crypto.X509Extension( 355 | b"basicConstraints", critical=True, value=b"CA:FALSE" 356 | ), 357 | _crypto.X509Extension( 358 | b"extendedKeyUsage", 359 | critical=True, 360 | value=b"clientAuth,serverAuth", 361 | ), 362 | _crypto.X509Extension( 363 | b"subjectAltName", critical=False, value=subjectAltName 364 | ), 365 | _crypto.X509Extension( 366 | b"subjectKeyIdentifier", 367 | critical=False, 368 | value=b"hash", 369 | subject=cert, 370 | ), 371 | ] 372 | cert.add_extensions(extensions) 373 | # subjectKeyIdentifier has to be present before adding auth ident 374 | extensions = [ 375 | _crypto.X509Extension( 376 | b"authorityKeyIdentifier", 377 | critical=False, 378 | value=b"issuer:always,keyid:always", 379 | issuer=ca.cert, 380 | ) 381 | ] 382 | cert.add_extensions(extensions) 383 | bits = cert.get_pubkey().bits() 384 | cert.sign(ca.key, HASH[bits]) 385 | pem = _crypto.dump_certificate(_crypto.FILETYPE_PEM, cert) 386 | return cls(CSR=CSR, pem=pem) 387 | -------------------------------------------------------------------------------- /caramel/scripts/__init__.py: -------------------------------------------------------------------------------- 1 | # package 2 | -------------------------------------------------------------------------------- /caramel/scripts/autosign.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python3 2 | 3 | """The caramel auto-signer daemon. 4 | This isn't necessary a _good_ idea, but it's part of examples of how 5 | you can use caramel for application signups. 6 | 7 | To work, you need to embed the root CA in your application (effectively pinning 8 | it). 9 | The client then generates a key (if none exists) and a CSR (based on the stored 10 | CA). It pushes this to the caramel server, and goes into a spin-loop, waiting 11 | for the key to get signed. 12 | 13 | The autosigner then automatically signs the CSR. 14 | The client gets it's certificate, and then connects to a second service (not 15 | quite implemented here) where the user adds contact information 16 | (email/password) which ties an identity to the private key. 17 | 18 | This can then be used to link multiple keys/applications to the same user, in a 19 | safe & secure manner. 20 | 21 | Autosigneer is implemented as it's own service, to make it obvious that you 22 | shouldn't have your private key accessible by the web-application. 23 | it.""" 24 | 25 | import argparse 26 | import concurrent.futures 27 | import datetime 28 | import logging 29 | import sys 30 | import time 31 | import uuid 32 | 33 | import transaction 34 | from sqlalchemy import create_engine 35 | 36 | import caramel.models as models 37 | from caramel import config 38 | from caramel.config import ( 39 | bootstrap, 40 | setup_logging, 41 | ) 42 | 43 | logger = logging.getLogger(__name__) 44 | 45 | 46 | def csr_sign(csr, ca, delta): 47 | """Signs a CSR and saves it in a transaction. 48 | Transaction so we won't have racing with the database. 49 | Also validates that it's a UUID for commonname.""" 50 | 51 | # Could have been by us, or before 52 | if csr.rejected: 53 | return 54 | 55 | try: 56 | uuid.UUID(csr.commonname) 57 | except ValueError: 58 | # not a valid uuid. Just ignore 59 | return 60 | 61 | with transaction.manager: 62 | cert = models.Certificate.sign(csr, ca, delta) 63 | cert.save() 64 | return 65 | 66 | 67 | def mainloop(delay, ca, delta): 68 | """Concurrent-enabled mainloop. 69 | Spins forever and signs all certificates that come in""" 70 | with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: 71 | while True: 72 | csrs = models.CSR.unsigned() 73 | futures = [executor.submit(csr_sign, csr, ca, delta) for csr in csrs] 74 | 75 | time.sleep(delay) 76 | for future in concurrent.futures.as_completed(futures): 77 | try: 78 | future.result() 79 | except Exception: 80 | logger.exception("Future failed") 81 | 82 | 83 | def cmdline(): 84 | """Basically just parsing the arguments and returning them""" 85 | parser = argparse.ArgumentParser() 86 | 87 | config.add_inifile_argument(parser) 88 | config.add_db_url_argument(parser) 89 | config.add_verbosity_argument(parser) 90 | config.add_ca_arguments(parser) 91 | 92 | parser.add_argument("--delay", help="How long to sleep. (ms)") 93 | parser.add_argument("--valid", help="How many hours the certificate is valid for") 94 | 95 | args = parser.parse_args() 96 | return args 97 | 98 | 99 | def error_out(message, closer): 100 | """Just log a message, and perform cleanup""" 101 | logger.error(message) 102 | closer() 103 | sys.exit(1) 104 | 105 | 106 | def main(): 107 | """Main, as called from the script instance by pyramid""" 108 | args = cmdline() 109 | config_path = args.inifile 110 | 111 | setup_logging(config_path) 112 | config.configure_log_level(args) 113 | 114 | env = bootstrap(config_path, dburl=args.dburl) 115 | settings, closer = env["registry"].settings, env["closer"] 116 | 117 | db_url = config.get_db_url(args, settings) 118 | engine = create_engine(db_url) 119 | 120 | models.init_session(engine) 121 | delay = int(settings.get("delay", 500)) / 1000 122 | valid = int(settings.get("valid", 3)) 123 | delta = datetime.timedelta(days=0, hours=valid) 124 | del valid 125 | 126 | try: 127 | ca_cert_path, ca_key_path = config.get_ca_cert_key_path(args, settings) 128 | except ValueError as error: 129 | error_out(str(error), closer) 130 | ca = models.SigningCert.from_files(ca_cert_path, ca_key_path) 131 | mainloop(delay, ca, delta) 132 | 133 | 134 | if __name__ == "__main__": 135 | logging.basicConfig() 136 | -------------------------------------------------------------------------------- /caramel/scripts/generate_ca.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | 4 | import argparse 5 | import datetime 6 | import os 7 | import uuid 8 | 9 | import OpenSSL.crypto as _crypto 10 | 11 | from caramel import config 12 | from caramel.config import ( 13 | get_appsettings, 14 | setup_logging, 15 | ) 16 | 17 | REQ_VERSION = 0x00 18 | VERSION = 0x2 19 | CA_BITS = 4096 20 | # Subject attribs, in order. 21 | ATTRIBS_TO_KEEP = ("C", "ST", "L", "O", "OU", "CN") 22 | CA_YEARS = 24 # Beware of unixtime ;) 23 | 24 | CA_EXTENSIONS = [ 25 | # Key usage for a CA cert. 26 | _crypto.X509Extension( 27 | b"basicConstraints", critical=True, value=b"CA:true, pathlen:0" 28 | ), 29 | # no cRLSign as we do not use CRLs in caramel. 30 | _crypto.X509Extension(b"keyUsage", critical=True, value=b"keyCertSign"), 31 | ] 32 | 33 | 34 | # Hack hack. :-) 35 | def CA_LIFE(): 36 | d = datetime.date.today() 37 | t = datetime.date(d.year + CA_YEARS, d.month, d.day) 38 | return int((t - d).total_seconds()) 39 | 40 | 41 | # adapted from models.py 42 | def components(subject): 43 | comps = subject.get_components() 44 | return dict((n.decode("utf8"), v.decode("utf8")) for n, v in comps) 45 | 46 | 47 | def matching_template(x509, cacert): 48 | """Takes a subject as a dict, and returns if all required fields 49 | match. Otherwise raises exception""" 50 | 51 | def later_check(subject): 52 | """Check that the last two fields in subject are OU, CN""" 53 | pair = subject[-1] 54 | if pair[0].decode("utf8") != "CN": 55 | raise ValueError("CN needs to be last in subject") 56 | 57 | pair = subject[-2] 58 | if pair[0].decode("utf8") != "OU": 59 | raise ValueError("OU needs to be second to last") 60 | 61 | casubject = cacert.get_subject().get_components() 62 | subject = x509.get_subject().get_components() 63 | later_check(casubject) 64 | later_check(subject) 65 | 66 | casubject = casubject[:-2] 67 | subject = subject[:-2] 68 | 69 | for ca, sub in zip(casubject, subject): 70 | if ca != sub: 71 | raise ValueError("Subject needs to match CA cert:" "{}".format(casubject)) 72 | 73 | 74 | def sign_req(req, cacert, cakey): 75 | # Validate Subject contents. Not necessary for CA gen, but kept anyhow 76 | matching_template(req, cacert) 77 | 78 | # Validate signature 79 | req.verify(req.get_pubkey()) 80 | request_subject = components(req.get_subject()) 81 | 82 | cert = _crypto.X509() 83 | subject = cert.get_subject() 84 | cert.set_serial_number(int(uuid.uuid1())) 85 | cert.set_version(VERSION) 86 | 87 | for attrib in ATTRIBS_TO_KEEP: 88 | if request_subject.get(attrib): 89 | setattr(subject, attrib, request_subject[attrib]) 90 | 91 | issuer_subject = cert.get_subject() 92 | cert.set_issuer(issuer_subject) 93 | cert.set_pubkey(req.get_pubkey()) 94 | 95 | # Validity times 96 | cert.gmtime_adj_notBefore(0) 97 | cert.gmtime_adj_notAfter(CA_LIFE()) 98 | 99 | cert.add_extensions(CA_EXTENSIONS) 100 | 101 | cacert = cert 102 | 103 | extension = _crypto.X509Extension( 104 | b"subjectKeyIdentifier", critical=False, value=b"hash", subject=cert 105 | ) 106 | cert.add_extensions([extension]) 107 | 108 | # We need subjectKeyIdentifier to be added before we can add 109 | # authorityKeyIdentifier. 110 | extension = _crypto.X509Extension( 111 | b"authorityKeyIdentifier", 112 | critical=False, 113 | value=b"issuer:always,keyid:always", 114 | issuer=cacert, 115 | ) 116 | cert.add_extensions([extension]) 117 | 118 | cert.sign(cakey, "sha512") 119 | return cert 120 | 121 | 122 | def create_ca_req(subject): 123 | key = _crypto.PKey() 124 | key.generate_key(_crypto.TYPE_RSA, CA_BITS) 125 | 126 | req = _crypto.X509Req() 127 | req.set_version(REQ_VERSION) 128 | req.set_pubkey(key) 129 | 130 | x509subject = req.get_subject() 131 | for k, v in subject: 132 | setattr(x509subject, k, v) 133 | 134 | req.add_extensions(CA_EXTENSIONS) 135 | 136 | req.sign(key, "sha512") 137 | return key, req 138 | 139 | 140 | def create_ca(subject): 141 | key, req = create_ca_req(subject) 142 | cert = sign_req(req, req, key) 143 | return key, req, cert 144 | 145 | 146 | def write_files(key, keyname, cert, certname): 147 | def writefile(data, name): 148 | with open(name, "w") as f: 149 | stream = data.decode("utf8") 150 | f.write(stream) 151 | 152 | _key = _crypto.dump_privatekey(_crypto.FILETYPE_PEM, key) 153 | writefile(_key, keyname) 154 | 155 | _cert = _crypto.dump_certificate(_crypto.FILETYPE_PEM, cert) 156 | writefile(_cert, certname) 157 | 158 | 159 | def cmdline(): 160 | parser = argparse.ArgumentParser() 161 | 162 | config.add_inifile_argument(parser) 163 | config.add_verbosity_argument(parser) 164 | config.add_ca_arguments(parser) 165 | 166 | args = parser.parse_args() 167 | return args 168 | 169 | 170 | def build_ca(keyname, certname): 171 | print("Enter CA settings, leave blank to not include") 172 | subject = {} 173 | subject["C"] = input("C [countryName (Code, 2 letters)]: ").upper() 174 | if subject["C"] and len(subject["C"]) != 2: 175 | raise ValueError("Country codes are two letters") 176 | 177 | subject["ST"] = input("ST [stateOrProvinceName]: ")[:20] 178 | subject["L"] = input("L [localityName]: ") 179 | subject["O"] = input("O [Organization]: ") 180 | subject["OU"] = input("OU [organizationalUnitName]: ") or "Caramel" 181 | subject["CN"] = "Caramel Signing Certificate" 182 | print("CN will be '{}'".format(subject["CN"])) 183 | 184 | template = [] 185 | for field in ATTRIBS_TO_KEEP: 186 | if field in subject and subject[field]: 187 | template.append((field, subject[field])) 188 | template = tuple(template) 189 | 190 | key, req, cert = create_ca(template) 191 | write_files(key=key, keyname=keyname, cert=cert, certname=certname) 192 | 193 | 194 | def main(): 195 | args = cmdline() 196 | config_path = args.inifile 197 | 198 | setup_logging(config_path) 199 | config.configure_log_level(args) 200 | 201 | settings = get_appsettings(config_path) 202 | 203 | try: 204 | ca_cert_path, ca_key_path = config.get_ca_cert_key_path(args, settings) 205 | except ValueError as error: 206 | print(error) 207 | exit() 208 | 209 | for f in ca_cert_path, ca_key_path: 210 | if os.path.exists(f): 211 | print("File already exists: {}. Refusing to corrupt.".format(f)) 212 | exit() 213 | else: 214 | dname = os.path.dirname(f) 215 | os.makedirs(dname, exist_ok=True) 216 | 217 | print("Will write key to {}".format(ca_key_path)) 218 | print("Will write cert to {}".format(ca_cert_path)) 219 | 220 | build_ca(keyname=ca_key_path, certname=ca_cert_path) 221 | -------------------------------------------------------------------------------- /caramel/scripts/initializedb.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | import argparse 4 | 5 | from sqlalchemy import create_engine 6 | 7 | import caramel.config as config 8 | from caramel.config import ( 9 | get_appsettings, 10 | setup_logging, 11 | ) 12 | from caramel.models import init_session 13 | 14 | 15 | def cmdline(): 16 | parser = argparse.ArgumentParser() 17 | 18 | config.add_inifile_argument(parser) 19 | config.add_db_url_argument(parser) 20 | config.add_verbosity_argument(parser) 21 | 22 | args = parser.parse_args() 23 | return args 24 | 25 | 26 | def main(): 27 | args = cmdline() 28 | config_path = args.inifile 29 | settings = get_appsettings(config_path) 30 | 31 | setup_logging(config_path) 32 | config.configure_log_level(args) 33 | 34 | db_url = config.get_db_url(args, settings) 35 | engine = create_engine(db_url) 36 | init_session(engine, create=True) 37 | -------------------------------------------------------------------------------- /caramel/scripts/tool.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python3 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | """Admin tool to sign/refresh certificates.""" 4 | 5 | import argparse 6 | import concurrent.futures 7 | import datetime 8 | import logging 9 | import sys 10 | 11 | import transaction 12 | from dateutil.relativedelta import relativedelta 13 | from pyramid.settings import asbool 14 | from sqlalchemy import create_engine 15 | 16 | from caramel import config, models 17 | 18 | LOG = logging.getLogger(name="caramel.tool") 19 | 20 | 21 | def cmdline(): 22 | """Parse commandline.""" 23 | parser = argparse.ArgumentParser() 24 | 25 | config.add_inifile_argument(parser) 26 | config.add_db_url_argument(parser) 27 | config.add_ca_arguments(parser) 28 | config.add_backdate_argument(parser) 29 | config.add_lifetime_arguments(parser) 30 | 31 | parser.add_argument( 32 | "--long", 33 | help="Generate a long lived cert(1 year)", 34 | action="store_true", 35 | ) 36 | 37 | parser.add_argument( 38 | "--list", 39 | help="List active requests, do nothing else", 40 | action="store_true", 41 | ) 42 | 43 | exclusives = parser.add_mutually_exclusive_group() 44 | exclusives.add_argument( 45 | "--sign", metavar="id", type=int, help="Sign the CSR with this id" 46 | ) 47 | exclusives.add_argument( 48 | "--reject", 49 | metavar="id", 50 | type=int, 51 | help="Reject the CSR with this id", 52 | ) 53 | 54 | cleanout = parser.add_mutually_exclusive_group() 55 | cleanout.add_argument( 56 | "--clean", 57 | metavar="id", 58 | type=int, 59 | help="Remove all older certificates for this CSR", 60 | ) 61 | cleanout.add_argument( 62 | "--wipe", 63 | metavar="id", 64 | type=int, 65 | help="Wipe all certificates for this CSR", 66 | ) 67 | 68 | bulk = parser.add_mutually_exclusive_group() 69 | bulk.add_argument( 70 | "--refresh", 71 | help="Sign all certificates that have a valid current signature.", 72 | action="store_true", 73 | ) 74 | 75 | bulk.add_argument( 76 | "--cleanall", 77 | help="Clean all older certificates.", 78 | action="store_true", 79 | ) 80 | 81 | args = parser.parse_args() 82 | # Didn't find a way to do this with argparse, but I didn't look too hard. 83 | return args 84 | 85 | 86 | def error_out(message, exc=None): 87 | """Print error message and exit with failure code.""" 88 | LOG.error(message) 89 | if exc is not None: 90 | LOG.error(str(exc)) 91 | sys.exit(1) 92 | 93 | 94 | def print_list(): 95 | """Print a list of certificates.""" 96 | valid_requests = models.CSR.list_csr_printable() 97 | 98 | def unsigned_last(csr): 99 | return (not csr[3], csr.id) 100 | 101 | valid_requests.sort(key=unsigned_last) 102 | 103 | for csr_id, csr_commonname, csr_sha256sum, not_after in valid_requests: 104 | not_after = "----------" if not_after is None else str(not_after) 105 | output = " ".join((str(csr_id), csr_commonname, csr_sha256sum, not_after)) 106 | # TODO: Add lifetime of latest (fetched?) cert for the key. 107 | print(output) 108 | 109 | 110 | def calc_lifetime(lifetime=relativedelta(hours=24)): 111 | """Calculate lifetime of certificate.""" 112 | now = datetime.datetime.utcnow() 113 | future = now + lifetime 114 | return future - now 115 | 116 | 117 | def csr_wipe(csr_id): 118 | """Wipe a certain csr.""" 119 | with transaction.manager: 120 | csr = models.CSR.query().get(csr_id) 121 | if not csr: 122 | error_out("ID not found") 123 | csr.certificates = [] 124 | csr.save() 125 | 126 | 127 | def csr_clean(csr_id): 128 | """Clean out old certs.""" 129 | with transaction.manager: 130 | csr = models.CSR.query().get(csr_id) 131 | if not csr: 132 | error_out("ID not found") 133 | certs = [csr.certificates.first()] 134 | csr.certificates = certs 135 | csr.save() 136 | 137 | 138 | def clean_all(): 139 | """Clean out all old requests.""" 140 | csrlist = models.CSR.refreshable() 141 | for csr in csrlist: 142 | csr_clean(csr.id) 143 | 144 | 145 | def csr_reject(csr_id): 146 | """Reject a request.""" 147 | with transaction.manager: 148 | csr = models.CSR.query().get(csr_id) 149 | if not csr: 150 | error_out("ID not found") 151 | csr.rejected = True 152 | csr.save() 153 | 154 | 155 | def csr_sign(csr_id, ca_cert, timedelta, backdate): 156 | """Sign a request with ca, valid for timedelta, or backdate as well.""" 157 | with transaction.manager: 158 | csr = models.CSR.query().get(csr_id) 159 | if not csr: 160 | error_out("ID not found") 161 | if csr.rejected: 162 | error_out("Refusing to sign rejected ID") 163 | 164 | cert = csr.certificates.first() 165 | if cert: 166 | today = datetime.datetime.utcnow() 167 | cur_lifetime = cert.not_after - cert.not_before 168 | # Cert hasn't expired, and currently has longer lifetime 169 | if (cert.not_after > today) and (cur_lifetime > timedelta): 170 | msg = ( 171 | "Currently has a valid certificate with {} lifetime, " 172 | "new certificate would have {} lifetime. \n" 173 | "Clean out existing certificates before shortening " 174 | "lifetime.\n" 175 | "The old certificate is still out there." 176 | ) 177 | error_out(msg.format(cur_lifetime, timedelta)) 178 | 179 | cert = models.Certificate.sign(csr, ca_cert, timedelta, backdate) 180 | cert.save() 181 | 182 | 183 | def refresh(csr, ca_cert, lifetime_short, lifetime_long, backdate): 184 | """Refresh a single csr.""" 185 | last = csr.certificates.first() 186 | old_lifetime = last.not_after - last.not_before 187 | # In a backdated cert, this is almost always true. 188 | if old_lifetime >= lifetime_long: 189 | cert = models.Certificate.sign(csr, ca_cert, lifetime_long, backdate) 190 | else: 191 | # Never backdate short-lived certs 192 | cert = models.Certificate.sign(csr, ca_cert, lifetime_short, False) 193 | with transaction.manager: 194 | cert.save() 195 | 196 | 197 | def csr_resign(ca_cert, lifetime_short, lifetime_long, backdate): 198 | """Re-sign all requests for lifetime.""" 199 | with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: 200 | try: 201 | csrlist = models.CSR.refreshable() 202 | except Exception as exc: # pylint:disable=broad-except 203 | error_out("Not found or some other error", exc=exc) 204 | futures = ( 205 | executor.submit( 206 | refresh, csr, ca_cert, lifetime_short, lifetime_long, backdate 207 | ) 208 | for csr in csrlist 209 | ) 210 | for future in concurrent.futures.as_completed(futures): 211 | try: 212 | future.result() 213 | except Exception as exc: # pylint:disable=broad-except 214 | LOG.error("Future failed: %s", exc) 215 | 216 | 217 | def main(): 218 | """Entrypoint of application.""" 219 | args = cmdline() 220 | logging.basicConfig(format="%(message)s", level=logging.WARNING) 221 | env = config.bootstrap(args.inifile, dburl=args.dburl) 222 | settings, closer = env["registry"].settings, env["closer"] 223 | db_url = config.get_db_url(args, settings) 224 | engine = create_engine(db_url) 225 | models.init_session(engine) 226 | settings_backdate = asbool(config.get_backdate(args, settings, default=False)) 227 | 228 | _short = int(config.get_lifetime_short(args, settings, default=48)) 229 | _long = int(config.get_lifetime_long(args, settings, default=7 * 24)) 230 | life_short = calc_lifetime(relativedelta(hours=_short)) 231 | life_long = calc_lifetime(relativedelta(hours=_long)) 232 | del _short, _long 233 | 234 | try: 235 | ca_cert_path, ca_key_path = config.get_ca_cert_key_path(args, settings) 236 | except ValueError as error: 237 | error_out("Error reading ca data", exc=error) 238 | 239 | ca_cert = models.SigningCert.from_files(ca_cert_path, ca_key_path) 240 | 241 | if life_short > life_long: 242 | error_out( 243 | f"Short lived certs ({life_short}) shouldn't last longer " 244 | f"than long lived certs ({life_long})" 245 | ) 246 | if args.list: 247 | print_list() 248 | closer() 249 | sys.exit(0) 250 | 251 | if args.reject: 252 | csr_reject(args.reject) 253 | 254 | if args.wipe: 255 | error_out("Not implemented yet") 256 | 257 | if args.clean: 258 | error_out("Not implemented yet") 259 | 260 | if args.cleanall: 261 | clean_all() 262 | 263 | if args.sign: 264 | if args.long: 265 | csr_sign(args.sign, ca_cert, life_long, settings_backdate) 266 | else: 267 | # Never backdate short lived certs 268 | csr_sign(args.sign, ca_cert, life_short, False) 269 | 270 | if args.refresh: 271 | csr_resign(ca_cert, life_short, life_long, settings_backdate) 272 | -------------------------------------------------------------------------------- /caramel/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ModioAB/caramel/2dce860cc437f8d97895bafa317fa4dffaa484a4/caramel/static/favicon.ico -------------------------------------------------------------------------------- /caramel/static/footerbg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ModioAB/caramel/2dce860cc437f8d97895bafa317fa4dffaa484a4/caramel/static/footerbg.png -------------------------------------------------------------------------------- /caramel/static/headerbg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ModioAB/caramel/2dce860cc437f8d97895bafa317fa4dffaa484a4/caramel/static/headerbg.png -------------------------------------------------------------------------------- /caramel/static/ie6.css: -------------------------------------------------------------------------------- 1 | * html img, 2 | * html .png{position:relative;behavior:expression((this.runtimeStyle.behavior="none")&&(this.pngSet?this.pngSet=true:(this.nodeName == "IMG" && this.src.toLowerCase().indexOf('.png')>-1?(this.runtimeStyle.backgroundImage = "none", 3 | this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "',sizingMethod='image')", 4 | this.src = "static/transparent.gif"):(this.origBg = this.origBg? this.origBg :this.currentStyle.backgroundImage.toString().replace('url("','').replace('")',''), 5 | this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.origBg + "',sizingMethod='crop')", 6 | this.runtimeStyle.backgroundImage = "none")),this.pngSet=true) 7 | );} 8 | #wrap{display:table;height:100%} 9 | -------------------------------------------------------------------------------- /caramel/static/middlebg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ModioAB/caramel/2dce860cc437f8d97895bafa317fa4dffaa484a4/caramel/static/middlebg.png -------------------------------------------------------------------------------- /caramel/static/pylons.css: -------------------------------------------------------------------------------- 1 | html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td 2 | { 3 | margin: 0; 4 | padding: 0; 5 | border: 0; 6 | outline: 0; 7 | font-size: 100%; /* 16px */ 8 | vertical-align: baseline; 9 | background: transparent; 10 | } 11 | 12 | body 13 | { 14 | line-height: 1; 15 | } 16 | 17 | ol, ul 18 | { 19 | list-style: none; 20 | } 21 | 22 | blockquote, q 23 | { 24 | quotes: none; 25 | } 26 | 27 | blockquote:before, blockquote:after, q:before, q:after 28 | { 29 | content: ''; 30 | content: none; 31 | } 32 | 33 | :focus 34 | { 35 | outline: 0; 36 | } 37 | 38 | ins 39 | { 40 | text-decoration: none; 41 | } 42 | 43 | del 44 | { 45 | text-decoration: line-through; 46 | } 47 | 48 | table 49 | { 50 | border-collapse: collapse; 51 | border-spacing: 0; 52 | } 53 | 54 | sub 55 | { 56 | vertical-align: sub; 57 | font-size: smaller; 58 | line-height: normal; 59 | } 60 | 61 | sup 62 | { 63 | vertical-align: super; 64 | font-size: smaller; 65 | line-height: normal; 66 | } 67 | 68 | ul, menu, dir 69 | { 70 | display: block; 71 | list-style-type: disc; 72 | margin: 1em 0; 73 | padding-left: 40px; 74 | } 75 | 76 | ol 77 | { 78 | display: block; 79 | list-style-type: decimal-leading-zero; 80 | margin: 1em 0; 81 | padding-left: 40px; 82 | } 83 | 84 | li 85 | { 86 | display: list-item; 87 | } 88 | 89 | ul ul, ul ol, ul dir, ul menu, ul dl, ol ul, ol ol, ol dir, ol menu, ol dl, dir ul, dir ol, dir dir, dir menu, dir dl, menu ul, menu ol, menu dir, menu menu, menu dl, dl ul, dl ol, dl dir, dl menu, dl dl 90 | { 91 | margin-top: 0; 92 | margin-bottom: 0; 93 | } 94 | 95 | ol ul, ul ul, menu ul, dir ul, ol menu, ul menu, menu menu, dir menu, ol dir, ul dir, menu dir, dir dir 96 | { 97 | list-style-type: circle; 98 | } 99 | 100 | ol ol ul, ol ul ul, ol menu ul, ol dir ul, ol ol menu, ol ul menu, ol menu menu, ol dir menu, ol ol dir, ol ul dir, ol menu dir, ol dir dir, ul ol ul, ul ul ul, ul menu ul, ul dir ul, ul ol menu, ul ul menu, ul menu menu, ul dir menu, ul ol dir, ul ul dir, ul menu dir, ul dir dir, menu ol ul, menu ul ul, menu menu ul, menu dir ul, menu ol menu, menu ul menu, menu menu menu, menu dir menu, menu ol dir, menu ul dir, menu menu dir, menu dir dir, dir ol ul, dir ul ul, dir menu ul, dir dir ul, dir ol menu, dir ul menu, dir menu menu, dir dir menu, dir ol dir, dir ul dir, dir menu dir, dir dir dir 101 | { 102 | list-style-type: square; 103 | } 104 | 105 | .hidden 106 | { 107 | display: none; 108 | } 109 | 110 | p 111 | { 112 | line-height: 1.5em; 113 | } 114 | 115 | h1 116 | { 117 | font-size: 1.75em; 118 | line-height: 1.7em; 119 | font-family: helvetica, verdana; 120 | } 121 | 122 | h2 123 | { 124 | font-size: 1.5em; 125 | line-height: 1.7em; 126 | font-family: helvetica, verdana; 127 | } 128 | 129 | h3 130 | { 131 | font-size: 1.25em; 132 | line-height: 1.7em; 133 | font-family: helvetica, verdana; 134 | } 135 | 136 | h4 137 | { 138 | font-size: 1em; 139 | line-height: 1.7em; 140 | font-family: helvetica, verdana; 141 | } 142 | 143 | html, body 144 | { 145 | width: 100%; 146 | height: 100%; 147 | } 148 | 149 | body 150 | { 151 | margin: 0; 152 | padding: 0; 153 | background-color: #fff; 154 | position: relative; 155 | font: 16px/24px NobileRegular, "Lucida Grande", Lucida, Verdana, sans-serif; 156 | } 157 | 158 | a 159 | { 160 | color: #1b61d6; 161 | text-decoration: none; 162 | } 163 | 164 | a:hover 165 | { 166 | color: #e88f00; 167 | text-decoration: underline; 168 | } 169 | 170 | body h1, body h2, body h3, body h4, body h5, body h6 171 | { 172 | font-family: NeutonRegular, "Lucida Grande", Lucida, Verdana, sans-serif; 173 | font-weight: 400; 174 | color: #373839; 175 | font-style: normal; 176 | } 177 | 178 | #wrap 179 | { 180 | min-height: 100%; 181 | } 182 | 183 | #header, #footer 184 | { 185 | width: 100%; 186 | color: #fff; 187 | height: 40px; 188 | position: absolute; 189 | text-align: center; 190 | line-height: 40px; 191 | overflow: hidden; 192 | font-size: 12px; 193 | vertical-align: middle; 194 | } 195 | 196 | #header 197 | { 198 | background: #000; 199 | top: 0; 200 | font-size: 14px; 201 | } 202 | 203 | #footer 204 | { 205 | bottom: 0; 206 | background: #000 url(footerbg.png) repeat-x 0 top; 207 | position: relative; 208 | margin-top: -40px; 209 | clear: both; 210 | } 211 | 212 | .header, .footer 213 | { 214 | width: 750px; 215 | margin-right: auto; 216 | margin-left: auto; 217 | } 218 | 219 | .wrapper 220 | { 221 | width: 100%; 222 | } 223 | 224 | #top, #top-small, #bottom 225 | { 226 | width: 100%; 227 | } 228 | 229 | #top 230 | { 231 | color: #000; 232 | height: 230px; 233 | background: #fff url(headerbg.png) repeat-x 0 top; 234 | position: relative; 235 | } 236 | 237 | #top-small 238 | { 239 | color: #000; 240 | height: 60px; 241 | background: #fff url(headerbg.png) repeat-x 0 top; 242 | position: relative; 243 | } 244 | 245 | #bottom 246 | { 247 | color: #222; 248 | background-color: #fff; 249 | } 250 | 251 | .top, .top-small, .middle, .bottom 252 | { 253 | width: 750px; 254 | margin-right: auto; 255 | margin-left: auto; 256 | } 257 | 258 | .top 259 | { 260 | padding-top: 40px; 261 | } 262 | 263 | .top-small 264 | { 265 | padding-top: 10px; 266 | } 267 | 268 | #middle 269 | { 270 | width: 100%; 271 | height: 100px; 272 | background: url(middlebg.png) repeat-x; 273 | border-top: 2px solid #fff; 274 | border-bottom: 2px solid #b2b2b2; 275 | } 276 | 277 | .app-welcome 278 | { 279 | margin-top: 25px; 280 | } 281 | 282 | .app-name 283 | { 284 | color: #000; 285 | font-weight: 700; 286 | } 287 | 288 | .bottom 289 | { 290 | padding-top: 50px; 291 | } 292 | 293 | #left 294 | { 295 | width: 350px; 296 | float: left; 297 | padding-right: 25px; 298 | } 299 | 300 | #right 301 | { 302 | width: 350px; 303 | float: right; 304 | padding-left: 25px; 305 | } 306 | 307 | .align-left 308 | { 309 | text-align: left; 310 | } 311 | 312 | .align-right 313 | { 314 | text-align: right; 315 | } 316 | 317 | .align-center 318 | { 319 | text-align: center; 320 | } 321 | 322 | ul.links 323 | { 324 | margin: 0; 325 | padding: 0; 326 | } 327 | 328 | ul.links li 329 | { 330 | list-style-type: none; 331 | font-size: 14px; 332 | } 333 | 334 | form 335 | { 336 | border-style: none; 337 | } 338 | 339 | fieldset 340 | { 341 | border-style: none; 342 | } 343 | 344 | input 345 | { 346 | color: #222; 347 | border: 1px solid #ccc; 348 | font-family: sans-serif; 349 | font-size: 12px; 350 | line-height: 16px; 351 | } 352 | 353 | input[type=text], input[type=password] 354 | { 355 | width: 205px; 356 | } 357 | 358 | input[type=submit] 359 | { 360 | background-color: #ddd; 361 | font-weight: 700; 362 | } 363 | 364 | /*Opera Fix*/ 365 | body:before 366 | { 367 | content: ""; 368 | height: 100%; 369 | float: left; 370 | width: 0; 371 | margin-top: -32767px; 372 | } 373 | -------------------------------------------------------------------------------- /caramel/static/pyramid-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ModioAB/caramel/2dce860cc437f8d97895bafa317fa4dffaa484a4/caramel/static/pyramid-small.png -------------------------------------------------------------------------------- /caramel/static/pyramid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ModioAB/caramel/2dce860cc437f8d97895bafa317fa4dffaa484a4/caramel/static/pyramid.png -------------------------------------------------------------------------------- /caramel/static/transparent.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ModioAB/caramel/2dce860cc437f8d97895bafa317fa4dffaa484a4/caramel/static/transparent.gif -------------------------------------------------------------------------------- /caramel/templates/mytemplate.pt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The Pyramid Web Application Development Framework 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 15 | 16 | 17 |
18 |
19 |
20 |
pyramid
21 |
22 |
23 |
24 |
25 |

26 | Welcome to ${project}, an application generated by
27 | the Pyramid web application development framework. 28 |

29 |
30 |
31 |
32 |
33 |
34 |

Search documentation

35 |
36 | 37 | 38 |
39 |
40 | 69 |
70 |
71 |
72 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /caramel/views.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | from datetime import datetime 4 | from hashlib import sha256 5 | 6 | from pyramid.httpexceptions import ( 7 | HTTPBadRequest, 8 | HTTPError, 9 | HTTPForbidden, 10 | HTTPLengthRequired, 11 | HTTPNotFound, 12 | HTTPRequestEntityTooLarge, 13 | ) 14 | from pyramid.response import Response 15 | from pyramid.view import view_config 16 | from sqlalchemy.exc import IntegrityError 17 | from sqlalchemy.orm.exc import NoResultFound 18 | 19 | from .models import ( 20 | CSR, 21 | AccessLog, 22 | SigningCert, 23 | ) 24 | 25 | # Maximum length allowed for csr uploads. 26 | # 2 kbyte should be enough for up to 4 kbit keys. 27 | # XXX: This should probably be handled outside of app (i.e. by the 28 | # server), or at least be configurable. 29 | _MAXLEN = 2 * 2**10 30 | 31 | 32 | def raise_for_length(req, limit=_MAXLEN): 33 | # two possible error cases: no length specified, or length exceeds limit 34 | # raise appropriate exception if either applies 35 | length = req.content_length 36 | if length is None: 37 | raise HTTPLengthRequired 38 | if length > limit: 39 | raise HTTPRequestEntityTooLarge("Max size: {0} kB".format(limit / 2**10)) 40 | 41 | 42 | def raise_for_subject(components, required_prefix): 43 | if len(components) < len(required_prefix): 44 | raise ValueError("Too few subject components") 45 | result = [(x, y) for x, y in zip(components, required_prefix) if x != y] 46 | if result: 47 | given, required = zip(*result) 48 | raise ValueError("{0} do not match {1}".format(given, required)) 49 | 50 | 51 | # XXX: Is this the right way? Catch-class JSON converter of Exceptions 52 | @view_config(context=HTTPError) 53 | def HTTPErrorToJson(exc, request): 54 | exc.json_body = {"status": exc.code, "title": exc.title, "detail": exc.detail} 55 | exc.content_type = "application/problem+json" 56 | request.response = exc 57 | return request.response 58 | 59 | 60 | @view_config(route_name="csr", request_method="POST", renderer="json") 61 | def csr_add(request): 62 | # XXX: do length check in middleware? server? 63 | raise_for_length(request) 64 | sha256sum = sha256(request.body).hexdigest() 65 | if sha256sum != request.matchdict["sha256"]: 66 | raise HTTPBadRequest("hash mismatch ({0})".format(sha256sum)) 67 | try: 68 | csr = CSR(sha256sum, request.body) 69 | except ValueError as err: 70 | raise HTTPBadRequest("crypto error: {0}".format(err)) 71 | 72 | # Verify the parts of the subject we care about 73 | ca = SigningCert.from_files(request.registry.settings["ca.cert"]) 74 | CA_PREFIX = ca.get_ca_prefix() 75 | try: 76 | raise_for_subject(csr.subject_components, CA_PREFIX) 77 | except ValueError as err: 78 | raise HTTPBadRequest("Bad subject: {0}".format(err)) 79 | 80 | # XXX: store things in DB 81 | try: 82 | csr.save() 83 | except IntegrityError: 84 | # XXX: is this what we want here? 85 | raise HTTPBadRequest("duplicate request") 86 | # We've accepted the signing request, but there's been no signing yet 87 | request.response.status_int = 202 88 | # JSON-rendered data (client could calculate this itself, and often will) 89 | return csr 90 | 91 | 92 | @view_config(route_name="cert", request_method="GET", renderer="json") 93 | def cert_fetch(request): 94 | # XXX: JSON-renderer at the moment, to dump 95 | sha256sum = request.matchdict["sha256"] 96 | try: 97 | csr = CSR.by_sha256sum(sha256sum) 98 | except NoResultFound: 99 | raise HTTPNotFound 100 | # XXX: Exceptions? remote_addr or client_addr? 101 | AccessLog(csr, request.remote_addr).save() 102 | if csr.rejected: 103 | raise HTTPForbidden 104 | cert = csr.certificates.first() 105 | if cert: 106 | if datetime.utcnow() < cert.not_after: 107 | # XXX: appropriate content-type is ... ? 108 | return Response( 109 | cert.pem, content_type="application/octet-stream", charset="UTF-8" 110 | ) 111 | request.response.status_int = 202 112 | return csr 113 | 114 | 115 | @view_config(route_name="ca", request_method="GET", renderer="string", http_cache=3600) 116 | def ca_fetch(request): 117 | ca_file = request.registry.settings["ca.cert"] 118 | ca = SigningCert.from_files(ca_file) 119 | return ca.pem.decode("utf8") 120 | 121 | 122 | @view_config( 123 | route_name="cabundle", request_method="GET", renderer="string", http_cache=3600 124 | ) 125 | def ca_bundle_fetch(request): 126 | """Attempt to return a bunle of all our intermediates""" 127 | bundle = ca_fetch(request) 128 | return bundle 129 | -------------------------------------------------------------------------------- /development.ini: -------------------------------------------------------------------------------- 1 | ### 2 | # app configuration 3 | # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html 4 | ### 5 | [app:main] 6 | use = egg:caramel 7 | 8 | # Point the following two settings on where you want your CA certificate & Key to live 9 | ca.cert = %(here)s/example_ca/caramel.ca.cert 10 | ca.key = %(here)s/example_ca/caramel.ca.key 11 | 12 | # This causes all certs to be backdated to the age of the start cert. 13 | # This is an ugly workaround for our embedded systems that lack RTC. 14 | backdate = False 15 | # Default to 48 hour certs 16 | lifetime.short = 48 17 | # Long term certs are for 30 days 18 | lifetime.long = 720 19 | 20 | 21 | # Change this to match your database 22 | # http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#database-urls 23 | sqlalchemy.url = sqlite:///%(here)s/caramel.sqlite 24 | 25 | 26 | pyramid.reload_templates = true 27 | pyramid.debug_authorization = false 28 | pyramid.debug_notfound = false 29 | pyramid.debug_routematch = false 30 | pyramid.default_locale_name = en 31 | pyramid.includes = 32 | pyramid_tm 33 | 34 | ### 35 | # wsgi server configuration 36 | ### 37 | [server:main] 38 | use = egg:waitress#main 39 | host = localhost 40 | port = 6543 41 | 42 | ### 43 | # logging configuration 44 | # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/logging.html 45 | ### 46 | 47 | [loggers] 48 | keys = root, caramel, sqlalchemy 49 | 50 | [handlers] 51 | keys = console 52 | 53 | [formatters] 54 | keys = generic 55 | 56 | [logger_root] 57 | level = INFO 58 | handlers = console 59 | 60 | [logger_caramel] 61 | level = DEBUG 62 | handlers = 63 | qualname = caramel 64 | 65 | [logger_sqlalchemy] 66 | level = INFO 67 | handlers = 68 | qualname = sqlalchemy.engine 69 | # "level = INFO" logs SQL queries. 70 | # "level = DEBUG" logs SQL queries and results. 71 | # "level = WARN" logs neither. (Recommended for production systems.) 72 | 73 | [handler_console] 74 | class = StreamHandler 75 | args = (sys.stderr,) 76 | level = NOTSET 77 | formatter = generic 78 | 79 | [formatter_generic] 80 | format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s 81 | -------------------------------------------------------------------------------- /doc/TODO.txt: -------------------------------------------------------------------------------- 1 | 2 | Serial: 3 | We need a serial storage (pref. associated with the root cert) 4 | serial should be unique to a certificate. The question is if we should re-use the serial-number for each cert we sign ( reissuing the same cert + sig with new timestamps ) or not. 5 | Revocation is always done based on Serial number. 6 | 7 | Quoth the RFC: 8 | The serial number is an integer assigned by the CA to each 9 | certificate. It MUST be unique for each certificate issued by a 10 | given CA (i.e., the issuer name and serial number identify a unique 11 | certificate). 12 | -------------------------------------------------------------------------------- /doc/deployment_notes.txt: -------------------------------------------------------------------------------- 1 | Deployment notes 2 | ---------------- 3 | 4 | These are mostly notes from deploying, also see 5 | http://pyramid-cookbook.readthedocs.org/en/latest/deployment/ 6 | 7 | 8 | Deploying on RHEL 6/ CentOS (to be tested/Verified) 9 | --------------------------------------------------- 10 | 11 | Install Apache & mod_fcgid 12 | Install SCL ( Software Collections Library, https://www.softwarecollections.org/ ) python33 13 | $ scl enable python33 bash 14 | $ virtualenv-3.3 /srv/ca.example.com/Environment 15 | $ chcon -t httpd_sys_content_t -R Environment 16 | $ chcon --ref /usr/bin/python Environment/bin/python 17 | $ chcon -R --ref /opt/rh/python33/root/usr/lib/python3.3/ Environment/li*/python3.3/ 18 | 19 | 20 | SELinux context inside the Virtualenv should be: 21 | ------------------------------------------------ 22 | drwxrwxr-x. admin_user git unconfined_u:object_r:var_t:s0 bin 23 | -rwxrwxr-x. admin_user git system_u:object_r:bin_t:s0 bin/python3 24 | drwxrwxr-x. admin_user git system_u:object_r:lib_t:s0 lib 25 | -rw-rw-r--. admin_user git unconfined_u:object_r:httpd_sys_content_t:s0 bin/activate 26 | -rw-rw-r--. admin_user git unconfined_u:object_r:httpd_sys_content_t:s0 bin/activate_this.py 27 | drwxrwxr-x. admin_user git system_u:object_r:lib_t:s0 lib/python3.3/ 28 | -rw-rw-r--. admin_user git system_u:object_r:lib_t:s0 lib/python3.3/site.py 29 | 30 | 31 | 32 | SELinux module that allows setpgid might be needed: 33 | [root@devel test]# cat setpgid.te 34 | 35 | module setpgid 1.0; 36 | 37 | require { 38 | type httpd_sys_script_t; 39 | class process setpgid; 40 | } 41 | 42 | #============= httpd_sys_script_t ============== 43 | allow httpd_sys_script_t self:process setpgid; 44 | 45 | 46 | --------------------------------------- 47 | # Above module was generated with audit2allow 48 | 49 | 50 | Apache 2.2 configuration 51 | ------------------------ 52 | 53 | Alias / /srv/ca.example.com/test/Foobar.launcher 54 | 55 | SetHandler fcgid-script 56 | Options +ExecCGI 57 | Order allow,deny 58 | Allow from all 59 | 60 | 61 | 62 | 63 | cat /srv/ca.example.com/test/Foobar.launcher 64 | #!/bin/bash 65 | PWD=`dirname $0` 66 | scl enable python33 "bash -c 'source $PWD/bin/activate; $PWD/testfcgi.py'" 67 | --- 68 | -rwxrwxr-x. apache git unconfined_u:object_r:httpd_sys_content_t:s0 /srv/ca.example.com/test/Foobar.launcher 69 | 70 | ----------------------------------------------- 71 | 72 | testfcgi.py contains: 73 | --------------------- 74 | 75 | #!/usr/bin/env python 76 | import sys 77 | 78 | from paste.deploy import loadapp 79 | from flup.server.fcgi_fork import WSGIServer 80 | 81 | app = loadapp('config:/srv/ca.example.com/test/fcgi.ini') 82 | server = WSGIServer(app) 83 | server.run() 84 | 85 | And has the following permissions 86 | --------------------------------- 87 | -rwxrwxr-x. spider git unconfined_u:object_r:httpd_sys_content_t:s0 testfcgi.py 88 | 89 | 90 | With SQLite as a database, apache needs write-access to the directory: 91 | --------------------------------------------------------------------- 92 | sudo chgrp apache project 93 | sudo chgrp apache project/*.sqlite 94 | chcon -t httpd_sys_rw_content_t project/*sqlite 95 | 96 | 97 | These are mostly notes from deploying, also see: 98 | http://pyramid-cookbook.readthedocs.org/en/latest/deployment/ 99 | -------------------------------------------------------------------------------- /doc/misc_reading.txt: -------------------------------------------------------------------------------- 1 | Other CA systems 2 | ============= 3 | OpenCA 4 | Dogtag (redhat Cert server) 5 | 6 | 7 | Some sources of interest 8 | ======================== 9 | 10 | 11 | Fixing X.509 certificates, 2014 12 | =============================== 13 | http://tersesystems.com/2014/03/20/fixing-x509-certificates/ 14 | 15 | 16 | 17 | x509 style guide, 2000 18 | ====================== 19 | https://www.cs.auckland.ac.nz/~pgut001/pubs/x509guide.txt 20 | 21 | 22 | RFC 5280, Internet X.509 Public Key Infrastructure Certificate 2008 23 | =================================================================== 24 | http://tools.ietf.org/search/rfc5280#section-4.1 25 | 26 | Certificate Transparency code on parsing ASN.1 x509 with python 27 | https://code.google.com/p/certificate-transparency/source/browse/src/python/ct/crypto/#crypto%2Fasn1 28 | 29 | 30 | 31 | 32 | Puppet style CA requests 33 | ======================== 34 | Interesting because of how they use custom OIDs 35 | http://docs.puppetlabs.com/puppet/latest/reference/ssl_attributes_extensions.html 36 | 37 | 38 | Random sources 39 | ============== 40 | http://www.mad-hacking.net/documentation/linux/security/ssl-tls/creating-csr.xml 41 | 42 | 43 | ASN.1 44 | ===== 45 | PyASN.1 Documentation 46 | http://pyasn1.sourceforge.net/ 47 | 48 | http://www.openssl.org/docs/apps/asn1parse.html 49 | 50 | 51 | RedHat Certificate System, Aka DogTag 52 | ===================================== 53 | https://access.redhat.com/site/documentation/en-US/Red_Hat_Certificate_System/8.0/html/Admin_Guide/CRL_Extensions.html 54 | https://access.redhat.com/site/documentation/en-US/Red_Hat_Certificate_System/8.0/html/Admin_Guide/Standard_X.509_v3_Certificate_Extensions.html 55 | 56 | 57 | 58 | Unsorted stuff 59 | ============== 60 | http://techglimpse.com/sha256-hash-certificate-openssl/ 61 | http://www.openssl.org/docs/apps/ca.html 62 | http://gnutls.org/manual/gnutls.html#X_002e509-certificates 63 | https://help.ubuntu.com/community/GnuTLS 64 | 65 | http://www.mad-hacking.net/documentation/linux/security/ssl-tls/creating-csr.xml 66 | -------------------------------------------------------------------------------- /doc/other_projects.txt: -------------------------------------------------------------------------------- 1 | Name : certmaster 2 | Summary : Remote certificate distribution framework 3 | URL : https://fedorahosted.org/certmaster 4 | Description : 5 | : certmaster is a easy mechanism for distributing SSL certificates 6 | 7 | Name : certmonger 8 | Summary : Certificate status monitor and PKI enrollment client 9 | URL : http://certmonger.fedorahosted.org 10 | Description : Certmonger is a service which is primarily concerned with getting your 11 | : system enrolled with a certificate authority (CA) and keeping it enrolled. 12 | 13 | 14 | 15 | Name : dogtag-pki 16 | Summary : Dogtag Public Key Infrastructure (PKI) Suite 17 | URL : http://pki.fedoraproject.org/ 18 | Description : The Dogtag Public Key Infrastructure (PKI) Suite is comprised of the following 19 | : six subsystems and a client (for use by a Token Management System): 20 | : 21 | : * Certificate Authority (CA) 22 | : * Data Recovery Manager (DRM) 23 | : * Online Certificate Status Protocol (OCSP) Manager 24 | : * Registration Authority (RA) 25 | : * Token Key Service (TKS) 26 | : * Token Processing System (TPS) 27 | : * Enterprise Security Client (ESC) 28 | : 29 | : Additionally, it provides a console GUI application used for server and 30 | : user/group administration of CA, DRM, OCSP, and TKS, javadocs on portions 31 | : of the Dogtag API, as well as various command-line tools used to assist with 32 | : a PKI deployment. 33 | : 34 | : To successfully deploy instances of a CA, DRM, OCSP, or TKS, 35 | : a Tomcat Web Server must be up and running locally on this machine. 36 | : 37 | : To successfully deploy instances of an RA, or TPS, 38 | : an Apache Web Server must be up and running locally on this machine. 39 | : 40 | : To meet the database storage requirements of each CA, DRM, OCSP, TKS, or TPS 41 | : instance, a 389 Directory Server must be up and running either locally on 42 | : this machine, or remotely over the attached network connection. 43 | : 44 | : To meet the database storage requirements of an RA, an SQLite database will 45 | : be created locally on this machine each time a new RA instance is created. 46 | : 47 | : After installation of this package, use the 'pkicreate' and 'pkiremove' 48 | : utilities to respectively create and remove PKI instances. 49 | -------------------------------------------------------------------------------- /fcgi-utils/caramel.wsgi: -------------------------------------------------------------------------------- 1 | from pyramid.paster import get_app, setup_logging 2 | ini_path = '/THIS/IS/WHERE/I/KEEP/MY/config.ini' 3 | setup_logging(ini_path) 4 | application = get_app(ini_path, 'main') 5 | -------------------------------------------------------------------------------- /fcgi-utils/paste-launcher.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | import sys 3 | 4 | from paste.deploy import loadapp 5 | from flup.server.fcgi_fork import WSGIServer 6 | 7 | config = sys.argv[1] 8 | 9 | app = loadapp(":".join(("config", config))) 10 | server = WSGIServer(app) 11 | server.run() 12 | -------------------------------------------------------------------------------- /fcgi-utils/paste-launcher.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | die () { 4 | echo >&2 "error:" "$@" 5 | exit 1 6 | } 7 | 8 | app="$(basename "$0" .sh)" 9 | here="$(dirname "$0")" 10 | 11 | venv_path="$(readlink -m "${here}/${app}-venv/")" 12 | cfg_path="$(readlink -m "${here}/${app}.ini")" 13 | 14 | venv="$(readlink -e "${venv_path}")" || die not found: "${venv_path}" 15 | cfg="$(readlink -e "${cfg_path}")" || die not found: "${cfg_path}" 16 | 17 | [ -r "${venv}/bin/activate" ] || \ 18 | die "${venv}" does not appear to be a virtualenv 19 | 20 | scl enable python33 "bash -c \ 21 | 'source \"${venv}/bin/activate\"; ${here}/paste-launcher.py \"${cfg}\"'" 22 | -------------------------------------------------------------------------------- /minimal.ini: -------------------------------------------------------------------------------- 1 | ### 2 | # NOTE: THIS IS ONLY FOR USE INSIDE CONTAINERS, SOME CONFIGURATION IS MISSING 3 | # HERE, FOR NORMAL TESTING USE development.ini 4 | # app configuration 5 | # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html 6 | ### 7 | [app:main] 8 | use = egg:caramel 9 | 10 | # Change this to match your database 11 | # http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#database-urls 12 | sqlalchemy.url = sqlite:////etc/caramel/caramel.sqlite 13 | 14 | 15 | 16 | pyramid.reload_templates = true 17 | pyramid.debug_authorization = false 18 | pyramid.debug_notfound = false 19 | pyramid.debug_routematch = false 20 | pyramid.default_locale_name = en 21 | pyramid.includes = 22 | pyramid_tm 23 | 24 | ### 25 | # wsgi server configuration 26 | ### 27 | [server:main] 28 | use = egg:waitress#main 29 | host = localhost 30 | port = 6543 31 | 32 | ### 33 | # logging configuration 34 | # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/logging.html 35 | ### 36 | 37 | [loggers] 38 | keys = root, caramel, sqlalchemy 39 | 40 | [handlers] 41 | keys = console 42 | 43 | [formatters] 44 | keys = generic 45 | 46 | [logger_root] 47 | level = INFO 48 | handlers = console 49 | 50 | [logger_caramel] 51 | level = DEBUG 52 | handlers = 53 | qualname = caramel 54 | 55 | [logger_sqlalchemy] 56 | level = INFO 57 | handlers = 58 | qualname = sqlalchemy.engine 59 | # "level = INFO" logs SQL queries. 60 | # "level = DEBUG" logs SQL queries and results. 61 | # "level = WARN" logs neither. (Recommended for production systems.) 62 | 63 | [handler_console] 64 | class = StreamHandler 65 | args = (sys.stderr,) 66 | level = NOTSET 67 | formatter = generic 68 | 69 | [formatter_generic] 70 | format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s 71 | -------------------------------------------------------------------------------- /pre-commit-checks: -------------------------------------------------------------------------------- 1 | #! /bin/bash -u 2 | # 3 | # License: GPLv3 or higher 4 | # XXX: Probably want _some_ output while setting up test environment, 5 | # but easy_install, pip install and setup.py install/test/develop 6 | # are all way to verbose, even with --quiet. 7 | 8 | flake8="$(git config hooks.flake8 || which flake8 2>/dev/null)" 9 | virtualenv="$(git config hooks.virtualenv || which virtualenv 2>/dev/null)" 10 | 11 | FLAKE8_ERROR="Could not find flake8. 12 | Please see README for details, or run: 13 | 14 | pip install flake8 15 | 16 | in your development VirtualEnv. 17 | " 18 | 19 | VIRTUALENV_ERROR="Could not find virtualenv. 20 | Point hooks.virtualenv to the virtualenv executable, or add it to your 21 | PATH. See README for details. 22 | " 23 | 24 | die () { 25 | [ -n "${1-}" ] && echo "Error: $1" 26 | exit ${2:-1} 27 | } >&2 28 | 29 | debug () { 30 | echo >&2 "$@" 31 | } 32 | 33 | # on_exit / add_on_exit code inspired by: 34 | # http://www.linuxjournal.com/content/use-bash-trap-statement-cleanup-temporary-files 35 | declare -a on_exit_items 36 | 37 | quoteargs () { 38 | local i str='' singlequote="'\''" 39 | for i; do 40 | str="$str '${i//\'/$singlequote}'" 41 | done 42 | printf %s "${str# }" 43 | } 44 | 45 | function on_exit() 46 | { 47 | for i in "${on_exit_items[@]}" 48 | do 49 | eval "$i" 50 | done 51 | } 52 | 53 | function add_on_exit() 54 | { 55 | local n=${#on_exit_items[*]} 56 | on_exit_items[$n]="$(quoteargs "$@")" 57 | if [[ $n -eq 0 ]]; then 58 | trap on_exit EXIT 59 | fi 60 | } 61 | 62 | ### Flake8 checks 63 | # Flake8 (pep8, rather) has a --diff option, but it seems to be flawed 64 | # (did not detect bad indentation, at least). We'll check both HEAD and 65 | # index, and diff the results of those. 66 | # XXX: renames are at the moment treated as all-new material. 67 | flake8_diff () { 68 | # flake8_diff a b 69 | # a and b assumed to be directories 70 | [ -z "${flake8}" ] && { 71 | # XXX: better way to do this? 72 | (die "${FLAKE8_ERROR}") 73 | return $? 74 | } 75 | 76 | local a="${1%%/}" b="${2%%/}" 77 | # use cut to trim the directory names (len+2 to get past the slash). 78 | ! fgrep -xv -f <($flake8 "${a}" | cut -c "$((${#a}+2))-") \ 79 | <($flake8 "${b}" | cut -c "$((${#b}+2))-") 80 | } 81 | 82 | ### Python testing 83 | # "python setup.py test" is much to verbose about thing not really 84 | # relevant. asd 85 | unittest_discover () { 86 | ### unittest_discover scratch_dir project_dir 87 | # initialize virtualenv, easy_install project, 88 | # run "python -m unittest discover" on project with venv python. 89 | [ -z "$virtualenv" ] && { 90 | # XXX: better way to do this? 91 | (die "${VIRTUALENV_ERROR}") 92 | return $? 93 | } 94 | 95 | local scratch="${1%%/}" proj="${2%%/}" 96 | local venv="${scratch}/venv" log="${scratch}/log" 97 | debug "Initialize virtualenv" 98 | $virtualenv "$venv" > /dev/null || { 99 | (die "Failed to create virtualenv.") 100 | return $? 101 | } 102 | debug "Install project (will probably take some time)" 103 | "${venv}/bin/easy_install" -Z "${proj}" &> "$log" || { 104 | cat "$log" 105 | (die "Test installation failed.") 106 | return $? 107 | } 108 | "${venv}/bin/python" -m unittest discover -v "$proj" 109 | } 110 | 111 | if git rev-parse --verify HEAD &>/dev/null 112 | then 113 | against=HEAD 114 | else 115 | # Initial commit: diff against an empty tree object 116 | against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 117 | fi 118 | 119 | exec 1>&2 120 | 121 | tmpdir="$(mktemp -d --tmpdir)" || die "Failed to create tempdir?!" 122 | add_on_exit rm -rf "$tmpdir" 123 | 124 | mkdir "${tmpdir}/old" "${tmpdir}/new" 125 | git checkout-index -q -a --prefix="${tmpdir}/new/" 126 | git archive $against | tar -C "${tmpdir}/old" -x -f - 127 | 128 | flake8_diff "${tmpdir}/old" "${tmpdir}/new" 129 | FLAKE8_STATUS=$? 130 | 131 | unittest_discover "$tmpdir" "${tmpdir}/new" 132 | TEST_STATUS=$? 133 | 134 | # "git diff --check" is not very clear without color, so force color=auto. 135 | git diff-index --check --cached --color=auto $against 136 | 137 | [ $? -eq 0 -a $FLAKE8_STATUS -eq 0 -a $TEST_STATUS -eq 0 ] || 138 | die "You've got some issues to deal with." 139 | -------------------------------------------------------------------------------- /production.ini: -------------------------------------------------------------------------------- 1 | ### 2 | # app configuration 3 | # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html 4 | ### 5 | [app:main] 6 | use = egg:caramel 7 | 8 | # Point the following two settings on where you want your CA certificate & Key to live 9 | ca.cert = /etc/pki/tls/certs/ca.example.com.cert 10 | ca.key = /etc/pki/tls/private/ca.example.com.key 11 | 12 | # This causes all certs to be backdated to the age of the start cert. 13 | # This is an ugly workaround for our embedded systems that lack RTC. 14 | backdate = False 15 | # We use 3 day periods 16 | lifetime.short = 72 17 | # Long term certs are for ~1 month 18 | lifetime.long = 729 19 | 20 | 21 | # Change this to match your database 22 | # http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#database-urls 23 | sqlalchemy.url = sqlite:////srv/ca.example.com/caramel.sqlite 24 | 25 | 26 | pyramid.reload_templates = false 27 | pyramid.debug_authorization = false 28 | pyramid.debug_notfound = false 29 | pyramid.debug_routematch = false 30 | pyramid.default_locale_name = en 31 | pyramid.includes = 32 | pyramid_tm 33 | 34 | ### 35 | # wsgi server configuration 36 | ### 37 | [server:main] 38 | use = egg:waitress#main 39 | host = 0.0.0.0 40 | port = 6543 41 | 42 | ### 43 | # logging configuration 44 | # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/logging.html 45 | ### 46 | 47 | [loggers] 48 | keys = root, caramel, sqlalchemy 49 | 50 | [handlers] 51 | keys = console 52 | 53 | [formatters] 54 | keys = generic 55 | 56 | [logger_root] 57 | level = WARN 58 | handlers = console 59 | 60 | [logger_caramel] 61 | level = WARN 62 | handlers = 63 | qualname = caramel 64 | 65 | [logger_sqlalchemy] 66 | level = WARN 67 | handlers = 68 | qualname = sqlalchemy.engine 69 | # "level = INFO" logs SQL queries. 70 | # "level = DEBUG" logs SQL queries and results. 71 | # "level = WARN" logs neither. (Recommended for production systems.) 72 | 73 | [handler_console] 74 | class = StreamHandler 75 | args = (sys.stderr,) 76 | level = NOTSET 77 | formatter = generic 78 | 79 | [formatter_generic] 80 | format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s 81 | -------------------------------------------------------------------------------- /request-certificate/caramelrequest/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ModioAB/caramel/2dce860cc437f8d97895bafa317fa4dffaa484a4/request-certificate/caramelrequest/__init__.py -------------------------------------------------------------------------------- /request-certificate/caramelrequest/certificaterequest.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | import distutils.spawn 4 | import hashlib 5 | import logging 6 | import os 7 | import subprocess 8 | import sys 9 | import time 10 | import tempfile 11 | from xml.etree import ElementTree as ET 12 | 13 | import requests 14 | 15 | OPENSSL_CNF = b""" 16 | # This definition stops the following lines choking if HOME isn't 17 | # defined. 18 | HOME = . 19 | RANDFILE = $ENV::HOME/.rnd 20 | #################################################################### 21 | [ req ] 22 | default_bits = 2048 23 | default_md = sha256 24 | default_keyfile = privkey.pem 25 | distinguished_name = req_distinguished_name 26 | attributes = req_attributes 27 | x509_extensions = v3_req # The extentions to add to the self signed cert 28 | string_mask = utf8only 29 | 30 | [ v3_req ] 31 | basicConstraints = CA:FALSE 32 | keyUsage = nonRepudiation, digitalSignature, keyEncipherment 33 | 34 | 35 | [ req_distinguished_name ] 36 | countryName = Country Name (2 letter code) 37 | countryName_default = AU 38 | countryName_min = 2 39 | countryName_max = 2 40 | stateOrProvinceName = State or Province Name (full name) 41 | stateOrProvinceName_default = Some-State 42 | localityName = Locality Name (eg, city) 43 | 0.organizationName = Organization Name (eg, company) 44 | 0.organizationName_default = Internet Widgits Pty Ltd 45 | organizationalUnitName = Organizational Unit Name (eg, section) 46 | commonName = Common Name (e.g. server FQDN or YOUR name) 47 | commonName_max = 64 48 | emailAddress = Email Address 49 | emailAddress_max = 64 50 | 51 | [ req_attributes ] 52 | challengePassword = A challenge password 53 | challengePassword_min = 4 54 | challengePassword_max = 20 55 | unstructuredName = An optional company name 56 | """ 57 | 58 | 59 | class CertificateRequestException(Exception): 60 | pass 61 | 62 | 63 | class CertificateRequest(object): 64 | def __init__(self, *, server, client_id): 65 | self.server = server 66 | self.client_id = client_id 67 | self.key_file_name = client_id + '.key' 68 | self.csr_file_name = client_id + '.csr' 69 | self.crt_temp_file_name = client_id + '.tmp' 70 | self.crt_file_name = client_id + '.crt' 71 | self.ca_cert_file_name = server + '.cacert' 72 | 73 | def perform(self): 74 | self.assert_openssl_available() 75 | self.assert_ca_cert_available() 76 | self.assert_ca_cert_verifies() 77 | subject = self.get_subject() 78 | self.ensure_valid_key_file() 79 | self.ensure_valid_csr_file(subject) 80 | self.request_cert_from_server() 81 | self.assert_temp_cert_verifies() 82 | self.rename_temp_cert() 83 | 84 | def assert_openssl_available(self): 85 | path = distutils.spawn.find_executable('openssl') 86 | if path is None: 87 | logging.error('Cannot find an openssl executable!') 88 | raise CertificateRequestException() 89 | 90 | def assert_ca_cert_available(self): 91 | if not os.path.isfile(self.ca_cert_file_name): 92 | logging.info('CA certificate file {} does not exist!' 93 | .format(self.ca_cert_file_name)) 94 | raise CertificateRequestException() 95 | 96 | def assert_ca_cert_verifies(self): 97 | result = call_silent('openssl', 'verify', 98 | '-CAfile', self.ca_cert_file_name, 99 | self.ca_cert_file_name) 100 | if 0 != result: 101 | logging.error('CA cert {} is not valid; bailing' 102 | .format(self.ca_cert_file_name)) 103 | raise CertificateRequestException() 104 | 105 | def assert_temp_cert_verifies(self): 106 | result = call_silent('openssl', 'verify', 107 | '-CAfile', self.ca_cert_file_name, 108 | self.crt_temp_file_name) 109 | if 0 != result: 110 | logging.error('Our new cert {} is not valid; bailing' 111 | .format(self.crt_temp_file_name)) 112 | raise CertificateRequestException() 113 | 114 | def rename_temp_cert(self): 115 | logging.info('Recieved certificate valid; moving it to {}' 116 | .format(self.crt_file_name)) 117 | os.rename(self.crt_temp_file_name, 118 | self.crt_file_name) 119 | 120 | def get_subject(self): 121 | output = check_output_silent('openssl', 122 | 'x509', 123 | '-subject', 124 | '-noout', 125 | '-in', self.ca_cert_file_name) 126 | _, value = decode_openssl_utf8(output).strip().split('subject= ', 1) 127 | prefix, original_cn = value.split('/CN=') 128 | if prefix == '/C=SE/OU=Caramel/L=Linköping/O=Modio AB/ST=Östergötland': 129 | prefix = '/C=SE/ST=Östergötland/L=Linköping/O=Modio AB/OU=Caramel' 130 | return '{}/CN={}'.format(prefix, self.client_id) 131 | 132 | def ensure_valid_key_file(self): 133 | have_key = False 134 | if not os.path.isfile(self.key_file_name): 135 | logging.info('Key file {} does not exist; generating it' 136 | .format(self.key_file_name)) 137 | elif 0 != call_silent('openssl', 138 | 'pkey', 139 | '-noout', 140 | '-in', self.key_file_name): 141 | logging.info('Key file {} is not valid; regenerating it' 142 | .format(self.key_file_name)) 143 | else: 144 | logging.info('Key file {} is valid; using it' 145 | .format(self.key_file_name)) 146 | have_key = True 147 | if not have_key: 148 | result = call_silent('openssl', 149 | 'genrsa', 150 | '-out', self.key_file_name, 151 | '2048') 152 | if result != 0: 153 | logging.error('Failed to generate private key!') 154 | raise CertificateRequestException() 155 | 156 | def ensure_valid_csr_file(self, subject): 157 | have_csr = False 158 | if not os.path.isfile(self.csr_file_name): 159 | logging.info(('Certificate signing request file {} ' + 160 | 'does not exist; generating it') 161 | .format(self.csr_file_name)) 162 | elif 0 != call_silent('openssl', 163 | 'req', 164 | '-noout', 165 | '-verify', 166 | '-in', self.csr_file_name, 167 | '-key', self.key_file_name): 168 | logging.info(('Certificate signing request file {} ' + 169 | 'is not valid; regenerating it') 170 | .format(self.csr_file_name)) 171 | else: 172 | logging.info(('Certificate signing request file {} is valid; ' + 173 | 'using it').format(self.csr_file_name)) 174 | have_csr = True 175 | if not have_csr: 176 | with tempfile.NamedTemporaryFile() as cnf: 177 | cnf.write(OPENSSL_CNF) 178 | cnf.flush() 179 | result = call_silent('openssl', 180 | 'req', 181 | '-config', cnf.name, 182 | '-sha256', 183 | '-utf8', 184 | '-new', 185 | '-key', self.key_file_name, 186 | '-out', self.csr_file_name, 187 | '-subj', subject) 188 | if result != 0: 189 | logging.error('Failed to create certificate signing request!') 190 | raise CertificateRequestException() 191 | 192 | def request_cert_from_server(self): 193 | csr, csr_hash = self.get_csr_and_hash() 194 | url = 'https://{}/{}'.format(self.server, csr_hash) 195 | 196 | session = requests.Session() 197 | session.verify = self.ca_cert_file_name 198 | 199 | response = session.get(url) 200 | while True: 201 | if response.status_code == 404: 202 | logging.info('CSR not posted; posting it') 203 | response = session.post(url, csr) 204 | elif response.status_code == 202 or response.status_code == 304: 205 | logging.info('CSR not processed yet; waiting ...') 206 | try: 207 | time.sleep(15) 208 | except KeyboardInterrupt: 209 | break 210 | response = session.get(url) 211 | elif response.status_code == 200: 212 | logging.info('Recieved certificate; saving it to {}' 213 | .format(self.crt_temp_file_name)) 214 | with open(self.crt_temp_file_name, 'wb') as f: 215 | f.write(response.content) 216 | break 217 | else: 218 | logging.error('Request failed: {}' 219 | .format(parse(response))) 220 | response.raise_for_status() 221 | break 222 | 223 | def get_csr_and_hash(self): 224 | with open(self.csr_file_name, 'rb') as f: 225 | csr = f.read() 226 | return csr, hashlib.sha256(csr).hexdigest() 227 | 228 | 229 | def printerr(text): 230 | sys.stderr.write(text + '\n') 231 | 232 | 233 | def parse(response): 234 | try: 235 | result = response.json() 236 | except Exception: 237 | result = parse_html(response) 238 | return result 239 | 240 | 241 | def parse_html(response): 242 | return ''.join((e.text or '') + (e.tail or '') 243 | for e in ET.fromstring(response.text).iterfind('body//')) 244 | 245 | 246 | def decode_openssl_utf8(text): 247 | return bytes(ord(x) for x in text.decode('unicode_escape')) \ 248 | .decode('utf-8') 249 | 250 | 251 | def call_silent(*args): 252 | return subprocess.call(args, 253 | stdout=subprocess.DEVNULL, 254 | stderr=subprocess.DEVNULL) 255 | 256 | 257 | def check_output_silent(*args): 258 | return subprocess.check_output(args, stderr=subprocess.DEVNULL) 259 | 260 | 261 | def main(): 262 | logging.basicConfig(level=logging.INFO, 263 | format='%(message)s') 264 | 265 | if (len(sys.argv) == 3): 266 | server = sys.argv[1] 267 | client_id = sys.argv[2] 268 | else: 269 | print('Usage: {} SERVER CLIENTID\n'.format(sys.argv[0]), 270 | file=sys.stderr) 271 | sys.exit(1) 272 | 273 | try: 274 | CertificateRequest(server=server, client_id=client_id).perform() 275 | except CertificateRequestException: 276 | sys.exit(1) 277 | 278 | 279 | if __name__ == '__main__': 280 | main() 281 | -------------------------------------------------------------------------------- /request-certificate/request-cert: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | from caramelrequest.certificaterequest import main 4 | 5 | main() 6 | -------------------------------------------------------------------------------- /request-certificate/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name='caramel-request-cert', 5 | version='0.1', 6 | packages=find_packages(), 7 | scripts=['request-cert'], 8 | 9 | install_requires=['requests'] 10 | ) 11 | -------------------------------------------------------------------------------- /scripts/caramel-deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ## This is our example deployment for our own servers 3 | ## This is an example of how we deploy python code, 4 | ## more documentation about that will follow. 5 | 6 | set -e 7 | : ${PROJECT:=caramel} 8 | : ${SERVER:=ca.example.com} 9 | 10 | TMPDIR=$(mktemp -d /tmp/${PROJECT}.XXXXX) 11 | trap "rm -rf $TMPDIR" EXIT 12 | REV=$(git rev-parse --verify --short HEAD) 13 | (git archive HEAD | tar -f - -xC "$TMPDIR") 14 | rsync -vr "$TMPDIR/" "$SERVER:/srv/$SERVER/$PROJECT-$REV" 15 | ssh -t "$SERVER" "/srv/$SERVER/$PROJECT-$REV/scripts/post-deploy.sh" "$PROJECT" "$REV" 16 | 17 | ## All done 18 | echo "**** All worked. Python has been restarted for the webserver" 19 | -------------------------------------------------------------------------------- /scripts/caramel-refresh.conf: -------------------------------------------------------------------------------- 1 | /etc/pki/tls/certs/www.example.com.csr;/etc/pki/tls/certs/www.example.com.crt 2 | /etc/pki/tls/certs/mail.example.com.csr;/etc/pki/tls/certs/mail.example.com.crt 3 | /etc/pki/tls/certs/custom.example.com.csr;/etc/pki/tls/certs/custom.example.com.crt;/etc/pki/tls/private/custom.example.com.pem 4 | -------------------------------------------------------------------------------- /scripts/caramel-refresh.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -euo pipefail 3 | : ${CONFIG:=/etc/caramel-refresh.conf} 4 | IFS=$'\n' 5 | 6 | die () { 7 | echo >&2 $'Error: \n'"$@" 8 | exit 1 9 | } 10 | 11 | if [ "$#" -lt 1 ]; 12 | then 13 | cat << EOF 14 | This is caramel-refresh! 15 | 16 | The first argument to caramel-refresh shall be the CA server URI 17 | The next argument to caramel-refresh can be CA server cert. 18 | 19 | We read a config file called /etc/caramel-refresh.conf. (or from CONFIG 20 | environment variable) 21 | 22 | $CONFIG is structured as per the following: 23 | 24 | One request per line. semicolon (;) separated fields. 25 | Field 0: CSR filename 26 | Field 1: CRT filename 27 | Field 2: PEM filename (optional, for lighttpd and others) 28 | 29 | The PEM filename will only be created if specified, and only if it 30 | exists. 31 | 32 | The PEM file will be concatenation of private key & cert, for Lighttpd 33 | and other tools that need that. 34 | Key is assumed to be named the same as csr, s/csr/key/. 35 | EOF 36 | die "Please add correct arguments" 37 | fi 38 | 39 | CURL_OPTS="--silent --show-error --connect-timeout 30 --max-time 60" 40 | POST_URL="$1" 41 | 42 | if [ "$#" -gt 1 ] 43 | then 44 | CA_CERT=$2 45 | test -s "$CA_CERT" || die "$CA_CERT missing" 46 | CURL_OPTS="${CURL_OPTS} --cacert $CA_CERT" 47 | fi 48 | 49 | type -p curl > /dev/null || die "We need curl in PATH" 50 | type -p sha256sum > /dev/null || die "We need sha256sum in PATH" 51 | test -s "$CONFIG" || die "$CONFIG should point to .csr files to be refreshed" 52 | 53 | TMPDIR=$(mktemp -d /tmp/caramel-refresh.XXXXXXXX) 54 | trap "rm -rf $TMPDIR" EXIT 55 | 56 | FAILED="" 57 | renew() { 58 | if [ "$#" -lt 2 ] 59 | then 60 | die "Need at least two posts in the config file, separated by ;" 61 | fi 62 | 63 | CSR="$1" 64 | CRT="$2" 65 | PEM="" 66 | 67 | if [ "$#" -gt 3 ] 68 | then 69 | PEM="$3" 70 | KEY=${CSR/.csr/.key} 71 | test -s "$PEM" || die "$PEM: found in config but missing" 72 | test -s "$KEY" || die "$PEM: Found but $KEY missing" 73 | fi 74 | 75 | test -z $CSR && die "Each line in the config is: csr filename;cert filename;pem filename" 76 | test -s "$CSR" || die "$CSR: invalid file match in config" 77 | test -s "$CRT" || die "$CRT: needs to exist." 78 | 79 | # Expansion done below, otherwise you get fun time debugging. 80 | IFS=$'\n\ ' 81 | echo "Processing: $CSR => $CRT" 82 | 83 | CSRSUM=$(sha256sum "$CSR" |cut -f1 -d" ") 84 | CERTOUT=$TMPDIR/$CSRSUM 85 | STATUS=$(curl ${CURL_OPTS} -w '%{http_code}' --url ${POST_URL}/${CSRSUM} -o $CERTOUT) 86 | if [ $STATUS -eq 200 ] 87 | then 88 | cat $CERTOUT > "$CRT" 89 | if [ ! -z "$PEM" ] 90 | then 91 | cat "$KEY" "$CRT" > $PEM 92 | fi 93 | else 94 | FAILED="${FAILED}${CSR} => HTTP Status: ${STATUS}"$'\n' 95 | fi 96 | rm -f $CERTOUT 97 | } 98 | 99 | IFS=$'\n' 100 | for line in $(<$CONFIG) 101 | do 102 | split=$(echo "$line" | tr ";" "\n") 103 | renew $split 104 | done 105 | 106 | test -z "$FAILED" || die "$FAILED" 107 | echo "all done" 108 | -------------------------------------------------------------------------------- /scripts/caramel_launcher.ini: -------------------------------------------------------------------------------- 1 | ### 2 | # app configuration 3 | # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html 4 | ### 5 | [app:main] 6 | use = egg:caramel 7 | 8 | # Point the following two settings on where you want your CA certificate & Key to live 9 | ca.cert = %(ca_cert)s 10 | ca.key = %(ca_key)s 11 | 12 | # This causes all certs to be backdated to the age of the start cert. 13 | # This is an ugly workaround for our embedded systems that lack RTC. 14 | backdate = False 15 | # Default to 48 hour certs 16 | lifetime.short = %(life_short)s 17 | # Long term certs are for 30 days 18 | lifetime.long = %(life_long)s 19 | 20 | 21 | # Change this to match your database 22 | # http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html#database-urls 23 | sqlalchemy.url = %(dburl)s 24 | 25 | 26 | pyramid.reload_templates = true 27 | pyramid.debug_authorization = false 28 | pyramid.debug_notfound = false 29 | pyramid.debug_routematch = false 30 | pyramid.default_locale_name = en 31 | pyramid.includes = 32 | pyramid_tm 33 | 34 | ### 35 | # wsgi server configuration 36 | ### 37 | [server:main] 38 | use = egg:waitress#main 39 | host = %(http_host)s 40 | port = %(http_port)s 41 | 42 | ### 43 | # logging configuration 44 | # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/logging.html 45 | ### 46 | 47 | [loggers] 48 | keys = root, caramel, sqlalchemy 49 | 50 | [handlers] 51 | keys = console 52 | 53 | [formatters] 54 | keys = generic 55 | 56 | [logger_root] 57 | level = %(log_level)s 58 | handlers = console 59 | 60 | [logger_caramel] 61 | level = DEBUG 62 | handlers = 63 | qualname = caramel 64 | 65 | [logger_sqlalchemy] 66 | level = INFO 67 | handlers = 68 | qualname = sqlalchemy.engine 69 | # "level = INFO" logs SQL queries. 70 | # "level = DEBUG" logs SQL queries and results. 71 | # "level = WARN" logs neither. (Recommended for production systems.) 72 | 73 | [handler_console] 74 | class = StreamHandler 75 | args = (sys.stderr,) 76 | level = NOTSET 77 | formatter = generic 78 | 79 | [formatter_generic] 80 | format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s 81 | -------------------------------------------------------------------------------- /scripts/caramel_launcher.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | ## Launch caramel with pserve as a Pyramid WSGI app using environment variables 3 | ## for configuration 4 | SCRIPT_HOME="$(dirname "$(realpath "$0")")" 5 | 6 | if [ -z "$1" ]; then 7 | PSERVE=pserve 8 | else 9 | PSERVE=$1 10 | fi 11 | 12 | exec $PSERVE "${SCRIPT_HOME}/caramel_launcher.ini" \ 13 | ca_cert="${CARAMEL_CA_CERT:-${BASEDIR}/example/caramel.ca.cert}" \ 14 | ca_key="${CARAMEL_CA_KEY:-${BASEDIR}/example/caramel.ca.key}" \ 15 | http_port="${CARAMEL_PORT:-6543}" \ 16 | http_host="${CARAMEL_HOST:-127.0.0.1}" \ 17 | life_short="${CARAMEL_LIFE_SHORT:-48}" \ 18 | life_long="${CARAMEL_LIFE_LONG:-720}" \ 19 | dburl="${CARAMEL_DBURL:-sqlite:///${BASEDIR}/caramel.sqlite}" \ 20 | log_level="${CARAMEL_LOG_LEVEL:-ERROR}" 21 | -------------------------------------------------------------------------------- /scripts/client-example.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | CA_DIR="$1" 3 | CA_CERT="$CA_DIR/caramel.ca.cert" 4 | MY_CRT="$CA_DIR/client.crt" 5 | MY_CSR="$CA_DIR/client.csr" 6 | MY_KEY="$CA_DIR/client.key" 7 | 8 | CLIENTID=$(cat /etc/machine-id) # For example machine ID or MAC-address 9 | CLIENTID=f11f05a9-773e-4b7e-b985-f5eb8fe18852 # or UUID https://xkcd.com/221/ 10 | 11 | SUBJECT="/C=SE/ST=Östergötland/L=Linköping/O=Muppar AB/OU=Muppar Teknik/CN=$CLIENTID" 12 | POST_URL=http://127.0.0.1:6543/ 13 | 14 | echo $SUBJECT 15 | 16 | if [ ! -f $MY_KEY ]; 17 | then 18 | rm -f $MY_CRT $MY_CSR 19 | openssl genrsa -out $MY_KEY 2048 20 | fi 21 | 22 | if [ ! -f $MY_CSR ]; 23 | then 24 | openssl req -new -key $MY_KEY -out $MY_CSR -utf8 -sha256 -subj "$SUBJECT" 25 | ## Upload csr 26 | fi 27 | 28 | CSRSUM=$(sha256sum $MY_CSR |cut -f1 -d" ") 29 | 30 | CURL_OPTS="--silent --show-error --remote-time --connect-timeout 300 --max-time 600 --cacert $CA_CERT" 31 | 32 | # The logic here is fun. 33 | # If I don't have a cert, we try to download it. 34 | # if we get 404 from downloading it, we upload the CSR. 35 | 36 | # if we _have_ a cert, we authorize ourselves using it. 37 | # If we _have_ a cert, we try to download a newer version. 38 | # if that 404s, we upload the CSR. 39 | # This is so that "older" clients will re-generate their certs 40 | 41 | # This means that the current states are : 42 | # 404 = No CSR pushed 43 | # 202: CSR pushed, not signed yet. ( nothing to do, try again later) 44 | # 200: Check timestamp if we want to download. 45 | 46 | if [ -f $MY_CRT ]; 47 | then 48 | # Check if newer ( -z ) 49 | # and use ssl client auth with key+cert 50 | 51 | CURL_OPTS="${CURL_OPTS} --key ${MY_KEY} --cert ${MY_CRT} -z ${MY_CRT}" 52 | fi 53 | 54 | ## Try: 55 | # Download cert ( if newer than what we have ) 56 | # if 202: 57 | # wait until later. ( uploaded, not signed ) 58 | # if 304: 59 | # do nothing 60 | # if 404 61 | # upload CSR 62 | 63 | STATUS=$(curl ${CURL_OPTS} -w '%{http_code}' --url ${POST_URL}/"${CSRSUM}" -o "${CA_DIR}/${CSRSUM}") 64 | 65 | if [ $STATUS -eq 200 ]; 66 | then 67 | mv $CA_DIR/$CSRSUM $MY_CRT 68 | fi 69 | 70 | if [ $STATUS -eq 202 -o $STATUS -eq 304 ]; 71 | then 72 | echo Not processed yet. waiting. 73 | # Or already in place 74 | rm -f $CSRSUM 75 | fi 76 | 77 | if [ $STATUS -eq 404 ]; 78 | then 79 | rm -f "$CA_DIR/$CSRSUM" 80 | curl ${CURL_OPTS} --data-binary @$MY_CSR ${POST_URL}/${CSRSUM} 81 | echo "" # ugly "hack" to guarantee new line before next command 82 | fi 83 | -------------------------------------------------------------------------------- /scripts/post-deploy.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | ## This script are tasks to be done on the server after initial deployment. 3 | ## This includes setting up local environments and virtualenvs 4 | ## This should only be called from "deploy-caramel.sh" 5 | 6 | set -e 7 | ## get the paths 8 | : ${PIP_DOWNLOAD_CACHE:=$HOME/pip-downloads} 9 | export PIP_DOWNLOAD_CACHE 10 | HERE="$(dirname "$(readlink -f "$0")")" 11 | PROJECT="$1" 12 | REV="$2" 13 | venv=/opt/venv/"$PROJECT-$REV" 14 | 15 | # Create new VirtualEnv 16 | scl enable python33 "virtualenv-3.3 $venv" 17 | /sbin/restorecon -vR "$venv" 18 | 19 | # Virtual env population & install 20 | scl enable python33 "bash -c \ 21 | 'source \"${venv}/bin/activate\";\ 22 | 'pip install -U pip'; 23 | 'pip install -U setuptools'; 24 | cd \"${HERE}\"; python setup.py install;'" 25 | 26 | /sbin/restorecon -vR "$venv" 27 | echo "Setting permissions" 28 | chmod -R go+rX "$HERE" 29 | chmod -R go+rX "$venv" 30 | 31 | # Permissions inside Virtual Env 32 | chcon -t httpd_sys_content_t "${venv}/bin/activate" 33 | 34 | 35 | ## Set up venv inside web-root 36 | cd "$HERE"/.. 37 | rm -f "$PROJECT".ini "$PROJECT"-venv 38 | ln -s "$HERE"/production.ini "$PROJECT".ini 39 | ln -s "$venv" "$PROJECT"-venv 40 | chcon -t httpd_sys_content_t "$PROJECT".ini 41 | # Below only works for root, do it manually. 42 | echo "As root: chcon -t httpd_sys_content_rw_t caramel.sqlite" 43 | # You probably want to do something to kill all old instances of caramel here below. 44 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [nosetests] 2 | match=^test 3 | nocapture=1 4 | cover-package=caramel 5 | with-coverage=1 6 | cover-erase=1 7 | 8 | [compile_catalog] 9 | directory = caramel/locale 10 | domain = caramel 11 | statistics = true 12 | 13 | [extract_messages] 14 | add_comments = TRANSLATORS: 15 | output_file = caramel/locale/caramel.pot 16 | width = 80 17 | 18 | [init_catalog] 19 | domain = caramel 20 | input_file = caramel/locale/caramel.pot 21 | output_dir = caramel/locale 22 | 23 | [update_catalog] 24 | domain = caramel 25 | input_file = caramel/locale/caramel.pot 26 | output_dir = caramel/locale 27 | previous = true 28 | 29 | [flake8] 30 | max-line-length = 88 31 | extend-ignore = E203 32 | 33 | # mypy related settings 34 | [mypy] 35 | plugins = sqlalchemy.ext.mypy.plugin 36 | [mypy-pyramid.*] 37 | ignore_missing_imports = True 38 | [mypy-transaction] 39 | ignore_missing_imports = True 40 | [mypy-zope.*] 41 | ignore_missing_imports = True 42 | 43 | [pylint] 44 | generated-members= 45 | scoped_session, 46 | Base, 47 | DBSession, 48 | 49 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | requires = [ 4 | "pyramid", 5 | "SQLAlchemy ~= 1.4.32", 6 | "transaction", 7 | "pyramid_tm", 8 | "zope.sqlalchemy >= 1.6", 9 | "waitress", 10 | "cryptography >= 38", 11 | "pyOpenSSL >= 22.0.0", 12 | "python-dateutil", 13 | # Transient dependency from pyramid->webob, 14 | # should be fixed in a later release of webob 15 | "legacy-cgi; python_version >= '3.13'" 16 | ] 17 | 18 | deplinks = [] 19 | 20 | setup( 21 | name="caramel", 22 | version="1.9.6", 23 | python_requires=">=3.7", 24 | description="caramel", 25 | long_description=""" 26 | Caramel is a certificate management system that makes it easy to use client 27 | certificates in web applications, mobile applications, embedded use and 28 | other places. It solves the certificate signing and certificate 29 | management headache, while attempting to be easy to deploy, maintain and 30 | use in a secure manner. 31 | 32 | Caramel makes it easier (it's never completely easy) to run your own 33 | certificate authority and manage and maintain keys and signing periods. 34 | 35 | Caramel focuses on reliably and continuously updating short-lived certificates 36 | where clients (and embedded devices) continue to "phone home" and fetch 37 | updated certificates. This means that we do not have to provide OCSP and 38 | CRL endpoints to handle compromised certificates, but only have to stop 39 | updating the certificate. This also means that expired certificates 40 | should be considered broken. 41 | """, 42 | classifiers=[ 43 | "Programming Language :: Python", 44 | "Framework :: Pyramid", 45 | "Topic :: Internet :: WWW/HTTP", 46 | "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", 47 | ], 48 | author="D.S. Ljungmark", 49 | author_email="spider@modio.se", 50 | url="https://github.com/MyTemp/caramel", 51 | keywords="web wsgi bfg pylons pyramid certificates x509 ca cert ssl tls", 52 | packages=find_packages(), 53 | include_package_data=True, 54 | zip_safe=False, 55 | test_suite="tests", 56 | install_requires=requires, 57 | dependency_links=deplinks, 58 | entry_points="""\ 59 | [paste.app_factory] 60 | main = caramel:main 61 | [console_scripts] 62 | caramel_initialize_db = caramel.scripts.initializedb:main 63 | caramel_tool = caramel.scripts.tool:main 64 | caramel_ca = caramel.scripts.generate_ca:main 65 | caramel_autosign = caramel.scripts.autosign:main 66 | """, 67 | ) 68 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | import unittest 4 | from itertools import zip_longest 5 | 6 | import transaction 7 | 8 | from caramel.models import ( 9 | DBSession, 10 | init_session, 11 | ) 12 | 13 | from . import fixtures 14 | 15 | 16 | class ModelTestCase(unittest.TestCase): 17 | @classmethod 18 | def setUpClass(cls): 19 | super(ModelTestCase, cls).setUpClass() 20 | # Clear existing session, if any. 21 | DBSession.remove() 22 | from sqlalchemy import create_engine 23 | 24 | engine = create_engine("sqlite://") 25 | init_session(engine, create=True) 26 | with transaction.manager: 27 | csr = fixtures.CSRData.initial() 28 | csr.save() 29 | 30 | def setUp(self): 31 | super(ModelTestCase, self).setUp() 32 | # Always run in a fresh session 33 | DBSession.remove() 34 | 35 | def assertSimilar(self, a, b, msg=None): 36 | if isinstance(b, fixtures.SimilarityComparable): 37 | a, b = b, a 38 | if isinstance(a, fixtures.SimilarityComparable): 39 | return self.assertTrue(a.match(b), msg) 40 | return self.assertEqual(a, b, msg) 41 | 42 | def assertSimilarSequence(self, seq1, seq2, msg=None): 43 | for a, b in zip_longest(seq1, seq2): 44 | self.assertSimilar(a, b) 45 | -------------------------------------------------------------------------------- /tests/ca_test_input.txt: -------------------------------------------------------------------------------- 1 | SE 2 | Östergötland 3 | Linköping 4 | Muppar AB 5 | Muppar Teknik -------------------------------------------------------------------------------- /tests/fixtures.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | from datetime import datetime, timedelta 4 | from hashlib import sha256 5 | from itertools import zip_longest 6 | from operator import attrgetter 7 | from textwrap import dedent 8 | 9 | from caramel import models, views 10 | 11 | day = timedelta(days=1) 12 | year = 365 * day # close enough 13 | now = datetime.now() 14 | 15 | 16 | class defaultproperty(object): 17 | def __init__(self, func): 18 | self.__doc__ = getattr(func, "__doc__", None) 19 | self.func = func 20 | 21 | def __get__(self, obj, objtype=None): 22 | return self if obj is None else self.func(obj) 23 | 24 | 25 | class SimilarityComparable(object): 26 | _match_excluded_attrs_ = ("match",) 27 | 28 | def match(self, other): 29 | excludes = set(getattr(self, "_match_excluded_attrs_", ())) 30 | attrs = [ 31 | attr 32 | for attr in dir(self) 33 | if not attr.startswith("_") and attr not in excludes 34 | ] 35 | if not attrs: 36 | return True 37 | getter = attrgetter(*attrs) 38 | try: 39 | return getter(self) == getter(other) 40 | except AttributeError: 41 | return False 42 | 43 | 44 | class AttributeCollection(object): 45 | def __init__(self, _base_=None, **kwds): 46 | if _base_: 47 | kwds = dict(_base_._attrs, **kwds) 48 | for k, v in kwds.items(): 49 | setattr(self, k, v) 50 | self._attrs = kwds 51 | 52 | 53 | class CSRFixture(AttributeCollection, SimilarityComparable): 54 | __relations = ( 55 | "accessed", 56 | "certificates", 57 | ) 58 | commonname: str 59 | pem: str 60 | certificates: list 61 | 62 | @property 63 | def _match_excluded_attrs_(self): 64 | return super(CSRFixture, self)._match_excluded_attrs_ + self.__relations 65 | 66 | @defaultproperty 67 | def sha256sum(self): 68 | return sha256(self.pem).hexdigest() 69 | 70 | def match(self, other): 71 | if not super(CSRFixture, self).match(other): 72 | return False 73 | for relation in self.__relations: 74 | related = getattr(self, relation, ()) 75 | if related: 76 | other_related = getattr(other, relation, ()) 77 | if not other_related: 78 | return False 79 | for a, b in zip_longest(related, other_related): 80 | if not a.match(b): 81 | return False 82 | return True 83 | 84 | def __call__(self): 85 | csr = models.CSR(self.sha256sum, self.pem) 86 | for relation in self.__relations: 87 | related = getattr(self, relation, ()) 88 | for relatee in related: 89 | relatee(csr).save() 90 | return csr 91 | 92 | 93 | class CertificateFixture(AttributeCollection, SimilarityComparable): 94 | not_before: datetime 95 | not_after: datetime 96 | common_subject: tuple 97 | pem: str 98 | 99 | def __call__(self, csr): 100 | # FIXME: adjust when models.Certificate gets a proper __init__ 101 | cert = models.Certificate(csr, self.pem) 102 | for name, value in self._attrs.items(): 103 | setattr(cert, name, value) 104 | cert.csr = csr 105 | return cert 106 | 107 | 108 | class AccessLogFixture(AttributeCollection, SimilarityComparable): 109 | when: datetime 110 | addr: str 111 | pem: str 112 | 113 | def __call__(self, csr): 114 | access = models.AccessLog(csr, self.addr) 115 | access.when = self.when 116 | return access 117 | 118 | 119 | # "Correct" subject prefix for test data 120 | subject_prefix = ( 121 | ("O", "Example inc."), 122 | ("OU", "Example Dept"), 123 | ) 124 | 125 | 126 | class CertificateData(object): 127 | initial = CertificateFixture( 128 | not_before=now - 2 * year, 129 | not_after=now + 2 * year, 130 | pem=dedent( 131 | """\ 132 | -----BEGIN CERTIFICATE----- 133 | MIIEVDCCAjygAwIBAgIBZTANBgkqhkiG9w0BAQsFADAmMSQwIgYDVQQDDBtDYXJh 134 | bWVsIFNpZ25pbmcgQ2VydGlmaWNhdGUwHhcNMTQwODA4MTM0NDA0WhcNMTQxMDA4 135 | MTM0NDA0WjAaMRgwFgYDVQQDDA9mb28uZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3 136 | DQEBAQUAA4IBDwAwggEKAoIBAQC+UOYhTExyWQL/mPzxvkd4xzju9Gcoxu5WZxxP 137 | +FjvsCKXkdMdzyTGYuaOulsRqyNmc8N73KJa9rlajIxdtR7duBwzX6Ddx2MmOLVL 138 | Q95X0jzdYR9iv6NX+bdYnoFUuzFt6N6Tf6OFS7IGiCeYqN7JTzTwlseJ7O4ozdsk 139 | vNlw7Cybb5RjqJQ/TRDSDWp1Fuq7FXanM+9Eaok0xqGty1TdMiEsCK8t7w3F1gd3 140 | bt48hld7cfe+OqdPxFLLtXv6wVM8EzcFYmwBGx7avXVS8aOsN6Oc3FZBfW0Fi0XD 141 | S6YO7WSzsRqciXolv/zPIvc1g6z5RkIPlgUaCtAdNBWkDG0hAgMBAAGjgZgwgZUw 142 | DAYDVR0TAQH/BAIwADAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAjAdBgNVHQ4EFgQU 143 | 79OVse0vdmb3VW6T9P7haHDOrhEwTgYDVR0jBEcwRYAUt9UtYpijdgeh1fObZHE4 144 | EBJPROGhKqQoMCYxJDAiBgNVBAMMG0NhcmFtZWwgU2lnbmluZyBDZXJ0aWZpY2F0 145 | ZYIBADANBgkqhkiG9w0BAQsFAAOCAgEAN8oppVaZlklLmvD1OfG0jf7SwWa03x6L 146 | Ej7xh0EbCeTZXNCmJNjiPpYG57Lf7OlXit9u1aJUQ5VXpUDmv1njb0jnB3EJBWf/ 147 | Y2KZbRYgXCpMUXxmfLrntULHAn/M3RLNi1ovwisiBqAU5/SZLcRq26Uwb8ygT0K7 148 | OA80JqjVzv53nKdUmDR0mopiWiU8c5BTi0R5+Q9vGov+DBcmrgatIHrtiXG8exGK 149 | m/DHZMAA93Vv/nh6GUe9uWI4mDhhLRSrdfkHoTPDqrFHIdH4OC+ljlPDRNhpkWAt 150 | FIzejEk5pqyqnAW4HHWM13vtOpddnXea+1y6PCX/9InAP5Tl1HMcq7BOgQa+EyPN 151 | NdzIRtdRnhtncMJUTCJpm2QEH09aPM3411tFpG3nZ6eTvo5f6oZS+epBVwNVqFXm 152 | xTbIEnBFnVBhQh2mXgJJsac2Oy8KGyBnVvGn6FKB6slrBjcIWKg+CDyiXMjwKhk5 153 | bjUvUdML4uWoGqdJfl+S+f+8m6S6F276p/uLI8Kb0NaE+z+LFRp2wrrC7DW65R+W 154 | eMdFWSu/IZZkoEaTrOeaqmLtQQt/4s66KKNOddftt+uLEMjce7foYQHo+qx9RI/1 155 | n4rH2rFn8rcQwSaRyE9NcOpirCur43MR42+LAfZq5s9j7CuQJTw6G0wvCHGqRIQ9 156 | X1qbQOxg6ig= 157 | -----END CERTIFICATE----- 158 | """ 159 | ).encode("utf8"), 160 | ) 161 | 162 | expired = CertificateFixture( 163 | not_before=initial.not_before, 164 | not_after=now - 1 * day, 165 | pem=dedent( 166 | """\ 167 | -----BEGIN CERTIFICATE----- 168 | MIIEVTCCAj2gAwIBAgIBaDANBgkqhkiG9w0BAQsFADAmMSQwIgYDVQQDDBtDYXJh 169 | bWVsIFNpZ25pbmcgQ2VydGlmaWNhdGUwHhcNMTQwODA4MTM1OTUxWhcNMTQxMDA4 170 | MTM1OTUxWjAbMRkwFwYDVQQDDBBzcGFtLmV4YW1wbGUuY29tMIIBIjANBgkqhkiG 171 | 9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnrzJ2qNhyIiCZvikFvPr0iEfzf27kTfHN+13 172 | 7bGuTAzmXFFrajz9K+leYcZR4sCPPRI8QjEUSYcngP1LKUrgzUSldjPrQGLsmx+8 173 | gLdi2JN1kPu6uMT97uB1RDKQpIMHGuV4mJKJku3sh6DJvQMjuMv8xOUXHtCw9jjc 174 | 6CLI9zeEZfM1RXsmRVxLx8HuwlF8ZNRjPGn5lEGIxTORpF1Mef5eTnGIg2kxwj8F 175 | 5aJP4ei9XS6gbYSFZekruT9Ivh41x4FYmx4bcGQfuIu+cG+XI3xGoNrm/IKMguMQ 176 | vwjBj2XnLHzskR5mz9YSLd9vi1nHl7b5u9GDtpmliNOvehaxjQIDAQABo4GYMIGV 177 | MAwGA1UdEwEB/wQCMAAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwHQYDVR0OBBYE 178 | FH/tkDyXntmyru3UFyYTO6UTOwjuME4GA1UdIwRHMEWAFLfVLWKYo3YHodXzm2Rx 179 | OBAST0ThoSqkKDAmMSQwIgYDVQQDDBtDYXJhbWVsIFNpZ25pbmcgQ2VydGlmaWNh 180 | dGWCAQAwDQYJKoZIhvcNAQELBQADggIBAD4r7SEyD6A61ORVjHHpw+5nZuaIf3Xs 181 | nZakE5I+wm/ZsVmWO3iOjAKdL2HartlDqGAvX5/w/sEoOkrpr48R7Uolm4ojYD2B 182 | Etxb4p9PDHmgT9Sc8nE2hOh8FdIUiGVLRJOuCmZqgk+EBIwB0zJQjREXHVZaN4dS 183 | wNNQGz46Vd2b6e4iRCJdgfOd2tuJi/WtvQORJkJ+HeTwLcN9LYY6d1bgups970DP 184 | Ve3QzxowNaRdX4SNtTmWs2BqcpYJV/Bx+q5r5CxhuDs5Jyvfmh9K7ux8z8Rv9THm 185 | UPJSXahBKLIYI8BYotXB9vpHvgWd15Opa3g+MV1Ego7KDKvdirTKnIcvafAi47vo 186 | kpAussllmvGr3wjDrGLlvbyBbbg44MpTzZrWspAjm9t0XFwkDDZGjY9l1zzqolDa 187 | KXbDda3LApBjWOr2QxsiwuOcemeekyiYusx5O4NqWJhGRVluvLpo5FWvuGZfoTCG 188 | X9QYUVrbsvhMMZR0VQDkJ7zfqbA8HvZ72qRpkC3MkOKDo4Ve9PffRjK+bamZM38I 189 | rvKws1E0w1WI1cK8ypefZhF8BiC/KUFMBw3bQAUQqdubv4eN81IX0PjnpfH+7wwA 190 | 7CRL6mRM5+q4ICfesXzUXpPYjgD2UexIjSJNoYjiu3aKpjwvrZ88t8hPR46Uac7E 191 | 5yvm61Agw/Tg 192 | -----END CERTIFICATE----- 193 | """ 194 | ).encode("utf8"), 195 | ) 196 | 197 | ca_cert = CertificateFixture( 198 | not_before=initial.not_before, 199 | not_after=initial.not_after, 200 | subject=( 201 | ("C", "SE"), 202 | ("ST", "Östergötland"), 203 | ("L", "Norrköping"), 204 | ("O", "Muppar AB"), 205 | ("OU", "Muppar Teknik"), 206 | ("CN", "Caramel Signing Certificate"), 207 | ), 208 | common_subject=( 209 | ("C", "SE"), 210 | ("ST", "Östergötland"), 211 | ("L", "Norrköping"), 212 | ("O", "Muppar AB"), 213 | ), 214 | pem=dedent( 215 | """\ 216 | -----BEGIN CERTIFICATE----- 217 | MIIGwDCCBKigAwIBAgIRAJSEOECNQRHkq2SMiaXBGsIwDQYJKoZIhvcNAQENBQAw 218 | gY4xCzAJBgNVBAYTAlNFMRcwFQYDVQQIDA7DlnN0ZXJnw7Z0bGFuZDEUMBIGA1UE 219 | BwwLTm9ycmvDtnBpbmcxEjAQBgNVBAoMCU11cHBhciBBQjEWMBQGA1UECwwNTXVw 220 | cGFyIFRla25pazEkMCIGA1UEAwwbQ2FyYW1lbCBTaWduaW5nIENlcnRpZmljYXRl 221 | MB4XDTE0MTIyNjIwNTU1M1oXDTM4MTIyNjIwNTU1M1owgY4xCzAJBgNVBAYTAlNF 222 | MRcwFQYDVQQIDA7DlnN0ZXJnw7Z0bGFuZDEUMBIGA1UEBwwLTm9ycmvDtnBpbmcx 223 | EjAQBgNVBAoMCU11cHBhciBBQjEWMBQGA1UECwwNTXVwcGFyIFRla25pazEkMCIG 224 | A1UEAwwbQ2FyYW1lbCBTaWduaW5nIENlcnRpZmljYXRlMIICIjANBgkqhkiG9w0B 225 | AQEFAAOCAg8AMIICCgKCAgEAtgt5ghocut1Qc7voPnpsuSWFvAC08e6LOk8ilQi8 226 | d9i2he19SFlNCFblhOLNsit+bBwFjWTIMsAaz8e1X7mQCR1sKKr1ShyvSTVw0UdQ 227 | uRNyYfP83h0vub4gOlJSvN4R816UP6zETHxRtdEZg7hlXY7NJsHnszEkxBicku2M 228 | an+CvB3//0EBSd20jUcDLR0K4fLNpku1gLrqfnejnZAnvUrW1LI2Nhhi10akiLNT 229 | a88rWicCwZtxCvwygjLJYL7FfL1NnmZwpYASorqldHu6RoUst3WL1r/dy0mpzftB 230 | kUG2Docf/3TxVkcdoC/Mjh3NqMAggJ3EdzTDEMGDUUG2EdtXXmT3GMEMW3y49Uww 231 | i4p36tIzVPpfjEVHFl4SJvafEiyCcCc9BxmtWLvXRFr2Q4dUmyDhdtNj9kT1w/94 232 | V71msSVlWdNvm7vPlV75tNtNAzdmFgs5Rnakkkc4QKyOttPJ+Cl+SO07fhziNVSU 233 | 5AWXLEHwJ9oUMp7H/FrvPwsQhMQIQ1dzQVoBTH473v3GRXFTwLseGgzITIN+vVv6 234 | K0ap1H/SkLfwuHMev6xXUF43w8kaDSvjHTN9Jad2IdjQ8siBuLlRBiLU4REn60lQ 235 | E/v5ttj2MWjXBIbt9yMWSYXtQCZTya778PZrGUJwIfEyzHfO2O0nODLuvuafxveo 236 | ShUCAwEAAaOCARUwggERMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQD 237 | AgIEMB0GA1UdDgQWBBQET+HX8lWrMux6W0Nd5heTB0TKWjCBywYDVR0jBIHDMIHA 238 | gBQET+HX8lWrMux6W0Nd5heTB0TKWqGBlKSBkTCBjjELMAkGA1UEBhMCU0UxFzAV 239 | BgNVBAgMDsOWc3RlcmfDtnRsYW5kMRQwEgYDVQQHDAtOb3Jya8O2cGluZzESMBAG 240 | A1UECgwJTXVwcGFyIEFCMRYwFAYDVQQLDA1NdXBwYXIgVGVrbmlrMSQwIgYDVQQD 241 | DBtDYXJhbWVsIFNpZ25pbmcgQ2VydGlmaWNhdGWCEQCUhDhAjUER5KtkjImlwRrC 242 | MA0GCSqGSIb3DQEBDQUAA4ICAQAx3jr30fHu9/AJpCnzs1nzNDoGwN7YdyZIWPUm 243 | uZJ2TPpMukK1bI38LXYS/bmjhgmc3MoyEridImm+FtFWFqDNASwcYpPEucH1HgEv 244 | gVp8MznhZIEJhB799hrDqLh3HRKAbgV3bz4zPFr3V6R3YRrMekVCBtcFHdDKq1Uy 245 | b4HwalrK6ZVxSr92DJy0Qyk5Zhtz1RGK1+7uECqWq5K5pTSMcw+MiLlESX+Brz4D 246 | EKABp4cLsOpHglasSNUVrmOaDg2qbz96PhsergjOeYQbakK87H/98pusFyPHkmYR 247 | nPbwiJi2D/9kxKwNkLiNI5oWRWY1ldcEE7C8hi8tOegNMu68UA2sx7Nhip3qUVcx 248 | M2JLOhBiq0BDCb+QpsF0NSeMyJCbkRogdYsIzGmCF51ubq/zYUE5mwvypD7CcdbI 249 | 947sucl+E8bLwcGMvOBEYUdSAisya8Qd7D2h/UwGHlBZu1SX3LCI7GopJ3LvkHG/ 250 | rF6tBrFEeXx1536rChzNal58wY+0HamTJQYFvh88OpbbwLP+UlPm4Gh0Rx3i61/I 251 | Op+poNAWLT5NACOX12yVfAcz3fWwxCoY62YoSfdUjH10BwZZssZdVIWdOGsCEOaL 252 | EybN1zenahQmhX4ljI5OSMYBP3gpkRu2HvP5SOwN28QHq2+mgCFxzdfdtiWoJ8a0 253 | 7eLmmg== 254 | -----END CERTIFICATE----- 255 | """ 256 | ).encode("utf8"), 257 | ) 258 | # FIXME: add more certificates here, once we have something to test. 259 | 260 | 261 | class AccessLogData(object): 262 | initial_1 = AccessLogFixture( 263 | when=CertificateData.initial.not_before + 30 * day, 264 | addr="127.0.0.1", # XXX: bytestring or unicode string? 265 | ) 266 | 267 | initial_2 = AccessLogFixture( 268 | when=now - 3 * day, 269 | addr="127.0.0.127", 270 | ) 271 | 272 | 273 | class CSRData(object): 274 | initial = CSRFixture( 275 | orgunit="Example Dept", 276 | commonname="foo.example.com", 277 | pem=dedent( 278 | """\ 279 | -----BEGIN CERTIFICATE REQUEST----- 280 | MIICjTCCAXUCAQIwSDEVMBMGA1UECgwMRXhhbXBsZSBpbmMuMRUwEwYDVQQLDAxF 281 | eGFtcGxlIERlcHQxGDAWBgNVBAMMD2Zvby5leGFtcGxlLmNvbTCCASIwDQYJKoZI 282 | hvcNAQEBBQADggEPADCCAQoCggEBAL5Q5iFMTHJZAv+Y/PG+R3jHOO70ZyjG7lZn 283 | HE/4WO+wIpeR0x3PJMZi5o66WxGrI2Zzw3vcolr2uVqMjF21Ht24HDNfoN3HYyY4 284 | tUtD3lfSPN1hH2K/o1f5t1iegVS7MW3o3pN/o4VLsgaIJ5io3slPNPCWx4ns7ijN 285 | 2yS82XDsLJtvlGOolD9NENINanUW6rsVdqcz70RqiTTGoa3LVN0yISwIry3vDcXW 286 | B3du3jyGV3tx9746p0/EUsu1e/rBUzwTNwVibAEbHtq9dVLxo6w3o5zcVkF9bQWL 287 | RcNLpg7tZLOxGpyJeiW//M8i9zWDrPlGQg+WBRoK0B00FaQMbSECAwEAAaAAMA0G 288 | CSqGSIb3DQEBCwUAA4IBAQBxkfl/Nq0y2u8Deq17OlB8WZfJnigEtFtMFstWNxNp 289 | Z3yxSFbaOYpB/+S0qOTjFbx1vQd8sSKTEqSgn2MkLhNsqtakWhejC+rrzVA02K6d 290 | J7uCylX8XVRJPjmt14E2LNLxGx1adV8St0tPrbzXMzr0ygpGaIITvd+ZzXr4CuGQ 291 | vao+T3EooEVQeFmWaoU6URUsqlp1itYzN1O+tvHv9pmCZ5UyTJlHQSc+cKJsUgE4 292 | O+jruZshnFL0KQybIokYGLLcb6NixdsCTSw+rfztuLUEEMP1ozNCgk8TX8mXWduM 293 | XIP49FHFe6IjLuj0ofRXiJPmS+4ToqRbNIBRoz7kSLov 294 | -----END CERTIFICATE REQUEST----- 295 | """ 296 | ).encode( 297 | "utf8" 298 | ), # py3 dedent can't handle bytes 299 | subject_components=( 300 | ("O", "Example inc."), 301 | ("OU", "Example Dept"), 302 | ("CN", "foo.example.com"), 303 | ), 304 | accessed=[ 305 | AccessLogData.initial_2, 306 | AccessLogData.initial_1, 307 | ], 308 | certificates=[ 309 | CertificateData.initial, 310 | ], 311 | ) 312 | 313 | with_expired_cert = CSRFixture( 314 | orgunit="Example Dept", 315 | commonname="spam.example.com", 316 | pem=dedent( 317 | """\ 318 | -----BEGIN CERTIFICATE REQUEST----- 319 | MIICjjCCAXYCAQIwSTEVMBMGA1UECgwMRXhhbXBsZSBpbmMuMRUwEwYDVQQLDAxF 320 | eGFtcGxlIERlcHQxGTAXBgNVBAMMEHNwYW0uZXhhbXBsZS5jb20wggEiMA0GCSqG 321 | SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCevMnao2HIiIJm+KQW8+vSIR/N/buRN8c3 322 | 7Xftsa5MDOZcUWtqPP0r6V5hxlHiwI89EjxCMRRJhyeA/UspSuDNRKV2M+tAYuyb 323 | H7yAt2LYk3WQ+7q4xP3u4HVEMpCkgwca5XiYkomS7eyHoMm9AyO4y/zE5Rce0LD2 324 | ONzoIsj3N4Rl8zVFeyZFXEvHwe7CUXxk1GM8afmUQYjFM5GkXUx5/l5OcYiDaTHC 325 | PwXlok/h6L1dLqBthIVl6Su5P0i+HjXHgVibHhtwZB+4i75wb5cjfEag2ub8goyC 326 | 4xC/CMGPZecsfOyRHmbP1hIt32+LWceXtvm70YO2maWI0696FrGNAgMBAAGgADAN 327 | BgkqhkiG9w0BAQsFAAOCAQEAf5SnEDewYNy4bu1bwga2alawbr+BQpysl/h53/aJ 328 | woJakG3E3+jSyAQ6Bu/j+YY+hTMbNX/sOyWMexS6w6HryQ6i/xvFZqhgN5ap/I6M 329 | k7V13j1LyxcTtlD773ikWq7F/+H76FgTAoE4oUmNvptej/C5eW5A1N150vMeecY/ 330 | 0nHIV+eXaZTCbg7UKr1xmR3tdu3DNnFC/BfaVv+Ul7s974k4g53ejLCvnCjMGVS3 331 | oQN1HuxKCScUJ9Vtr0dnBLGAf62vAqv5yZYhl9Qnt5EJ9OtspWm0e8FwTjNmoA/z 332 | qnvUxskzM2ItxVV9oa9YDTid0GbJvF67QJQyVIO0Vz4uwg== 333 | -----END CERTIFICATE REQUEST----- 334 | """ 335 | ).encode( 336 | "utf8" 337 | ), # py3 dedent can't handle bytes 338 | subject_components=( 339 | ("O", "Example inc."), 340 | ("OU", "Example Dept"), 341 | ("CN", "spam.example.com"), 342 | ), 343 | certificates=[ 344 | CertificateData.expired, 345 | ], 346 | ) 347 | 348 | good = CSRFixture( 349 | orgunit="Example Dept", 350 | commonname="bar.example.com", 351 | pem=dedent( 352 | """\ 353 | -----BEGIN CERTIFICATE REQUEST----- 354 | MIICjTCCAXUCAQIwSDEVMBMGA1UECgwMRXhhbXBsZSBpbmMuMRUwEwYDVQQLDAxF 355 | eGFtcGxlIERlcHQxGDAWBgNVBAMMD2Jhci5leGFtcGxlLmNvbTCCASIwDQYJKoZI 356 | hvcNAQEBBQADggEPADCCAQoCggEBAN7fng4vFo0P0+K1L64rADgXBDrwsa39p3tV 357 | 7GwY/LZ9crxUgwFKfVLM8rX4KAySiOXix8JF44jansXTOkcm8OjnOKVNIJX/5Pf3 358 | bRDSXcjodFIhPVzUynj8E5Z8rEB2ES9gwYDKIYVNnJa2nGmQVe7IgA5O7lNM6gse 359 | TqYlN3bmB9Dy/dY+ZVyts1p6aSOYMdAcJ7ojCco9HuYFav2hd7k2h4b4lCKvi7p2 360 | sx6DoKmnblmlvMlP9UdSq7wORkAUnMn5rlzdj5LnWsSB+JLBrQaSlsIfVeL0+5oB 361 | 6zrZI5hJPQiaLcet0v6a7M7UkOyJKiGJVCKYnO122D4Cu4lB2d0CAwEAAaAAMA0G 362 | CSqGSIb3DQEBCwUAA4IBAQAGJwl7vUlDg2L3KgnsNA9A4rMKfFn5fzdf6Z0X3HSY 363 | Zvi8XKkVAKd7aRUSg6jcJbOm0HNmBR+5SWzXUU62KQWuUCwz+dCyCbcEO/frG0IB 364 | HdOs/L4AJgHlIaxwisCLh5VQpj5w0ahhzVfLGWcCK1nbqjUTLcEFhvZviUPUugAD 365 | f7QdWNDBuZTrwXGTLsnhC5XQfsk0maXcNji79ziK4sMm5TU2599JmuWL2NTbqaCQ 366 | MN1FxWzEy4yXgzW8uv+lX6yyTtkfrC7e3LFiAuoUlBeD5GmsVd30Xz5iGnuQv3d0 367 | fekjT5Np8XIS2ERJmx4CIjs5VpE1FMNOMoJ35kQpkQaQ 368 | -----END CERTIFICATE REQUEST----- 369 | """ 370 | ).encode("utf8"), 371 | subject_components=( 372 | ("O", "Example inc."), 373 | ("OU", "Example Dept"), 374 | ("CN", "bar.example.com"), 375 | ), 376 | ) 377 | 378 | bad_signature = CSRFixture( # `good` with the subject of `initial` 379 | pem=dedent( 380 | """\ 381 | -----BEGIN CERTIFICATE REQUEST----- 382 | MIIBAjCBrQIBADBIMRUwEwYDVQQKDAxFeGFtcGxlIGluYy4xFTATBgNVBAsMDEV4 383 | YW1wbGUgRGVwdDEYMBYGA1UEAwwPZm9vLmV4YW1wbGUuY29tMFwwDQYJKoZIhvcN 384 | AQEBBQADSwAwSAJBAKk2sD6xi/gfO3TVnoGMhUmkPDD17/qYzEvDdw/kponLTdNF 385 | asGx1//giKSBqBpUFt+KTz3NofK9Pf2qWWDxyUECAwEAAaAAMA0GCSqGSIb3DQEB 386 | BQUAA0EAcsrzTdYBqlbq/JQaMSEoi64NmoxiC8GGzOaKlTxqRc7PKb+T1wN94PxJ 387 | faXw8kA8p0E6hmwFAE9QVkuTKvP/eg== 388 | -----END CERTIFICATE REQUEST----- 389 | """ 390 | ).encode("utf8"), 391 | ) 392 | 393 | truncated = CSRFixture( 394 | pem=dedent( 395 | """\ 396 | -----BEGIN CERTIFICATE REQUEST----- 397 | MIIBAjCBrQIBADBIMRUwEwYDVQQKDAxFeGFtcGxlIGluYy4xFTATBgNVBAsMDEV4 398 | YW1wbGUgRGVwdDEYMBYGA1UEAwwPYmFyLmV4YW1wbGUuY29tMFwwDQYJKoZIhvcN 399 | AQEBBQADSwAwSAJBAKk2sD6xi/gfO3TVnoGMhUmkPDD17/qYzEvDdw/kponLTdNF 400 | asGx1//giKSBqBpUFt+KTz3NofK9Pf2qWWDxyUECAwEAAaAAMA0GCSqGSIb3DQEB 401 | """ 402 | ).encode("utf8"), 403 | ) 404 | 405 | trailing_content = CSRFixture( 406 | pem=dedent( 407 | """\ 408 | -----BEGIN CERTIFICATE REQUEST----- 409 | MIIBAjCBrQIBADBIMRUwEwYDVQQKDAxFeGFtcGxlIGluYy4xFTATBgNVBAsMDEV4 410 | YW1wbGUgRGVwdDEYMBYGA1UEAwwPYmFyLmV4YW1wbGUuY29tMFwwDQYJKoZIhvcN 411 | AQEBBQADSwAwSAJBAKk2sD6xi/gfO3TVnoGMhUmkPDD17/qYzEvDdw/kponLTdNF 412 | asGx1//giKSBqBpUFt+KTz3NofK9Pf2qWWDxyUECAwEAAaAAMA0GCSqGSIb3DQEB 413 | BQUAA0EAcsrzTdYBqlbq/JQaMSEoi64NmoxiC8GGzOaKlTxqRc7PKb+T1wN94PxJ 414 | faXw8kA8p0E6hmwFAE9QVkuTKvP/eg== 415 | -----END CERTIFICATE REQUEST----- 416 | foo 417 | bar 418 | baz 419 | quux 420 | """ 421 | ).encode("utf8"), 422 | ) 423 | 424 | leading_content = CSRFixture( 425 | pem=dedent( 426 | """\ 427 | foo 428 | bar 429 | baz 430 | quux 431 | -----BEGIN CERTIFICATE REQUEST----- 432 | MIIBAjCBrQIBADBIMRUwEwYDVQQKDAxFeGFtcGxlIGluYy4xFTATBgNVBAsMDEV4 433 | YW1wbGUgRGVwdDEYMBYGA1UEAwwPYmFyLmV4YW1wbGUuY29tMFwwDQYJKoZIhvcN 434 | AQEBBQADSwAwSAJBAKk2sD6xi/gfO3TVnoGMhUmkPDD17/qYzEvDdw/kponLTdNF 435 | asGx1//giKSBqBpUFt+KTz3NofK9Pf2qWWDxyUECAwEAAaAAMA0GCSqGSIb3DQEB 436 | BQUAA0EAcsrzTdYBqlbq/JQaMSEoi64NmoxiC8GGzOaKlTxqRc7PKb+T1wN94PxJ 437 | faXw8kA8p0E6hmwFAE9QVkuTKvP/eg== 438 | -----END CERTIFICATE REQUEST----- 439 | """ 440 | ).encode("utf8"), 441 | ) 442 | 443 | multi_request = CSRFixture( 444 | pem=dedent( 445 | """\ 446 | -----BEGIN CERTIFICATE REQUEST----- 447 | MIIBAjCBrQIBADBIMRUwEwYDVQQKDAxFeGFtcGxlIGluYy4xFTATBgNVBAsMDEV4 448 | YW1wbGUgRGVwdDEYMBYGA1UEAwwPZm9vLmV4YW1wbGUuY29tMFwwDQYJKoZIhvcN 449 | AQEBBQADSwAwSAJBANBBe43zbCwPs1jRPPqgb6Otdqx9kg67Dgfoxh3Mly7b9JPp 450 | orKIs6zzoyMeLHLJYk+CwSHyeS1hc4zL+3A+k88CAwEAAaAAMA0GCSqGSIb3DQEB 451 | BQUAA0EALt6dIjlzG05KCfyiy2PJdAwcjC+mpHh3i4cJs50U+EnxBgX8QscOu382 452 | 72uukmhYBG1Xd1LN4S5RL9pcQ9KLaA== 453 | -----END CERTIFICATE REQUEST----- 454 | -----BEGIN CERTIFICATE REQUEST----- 455 | MIIBAjCBrQIBADBIMRUwEwYDVQQKDAxFeGFtcGxlIGluYy4xFTATBgNVBAsMDEV4 456 | YW1wbGUgRGVwdDEYMBYGA1UEAwwPYmFyLmV4YW1wbGUuY29tMFwwDQYJKoZIhvcN 457 | AQEBBQADSwAwSAJBAKk2sD6xi/gfO3TVnoGMhUmkPDD17/qYzEvDdw/kponLTdNF 458 | asGx1//giKSBqBpUFt+KTz3NofK9Pf2qWWDxyUECAwEAAaAAMA0GCSqGSIb3DQEB 459 | BQUAA0EAcsrzTdYBqlbq/JQaMSEoi64NmoxiC8GGzOaKlTxqRc7PKb+T1wN94PxJ 460 | faXw8kA8p0E6hmwFAE9QVkuTKvP/eg== 461 | -----END CERTIFICATE REQUEST----- 462 | """ 463 | ).encode("utf8"), 464 | ) 465 | 466 | not_pem = CSRFixture( 467 | pem=dedent( 468 | """\ 469 | Egg and Bacon 470 | Egg, Sausage and Bacon 471 | Egg and Spam 472 | Egg, Bacon and Spam 473 | Egg, Bacon, Sausage and Spam 474 | Spam, Bacon, Sausage and Spam 475 | Spam, Egg, Spam, Spam, Bacon and Spam 476 | Spam, Spam, Spam, Egg and Spam 477 | Spam, Spam, Spam, Spam, Spam, Spam, Baked Beans, 478 | Spam, Spam, Spam and Spam 479 | """ 480 | ).encode("utf8"), 481 | ) 482 | 483 | empty = CSRFixture(pem=b"") 484 | 485 | bad_sha = CSRFixture(good, sha256sum=not_pem.sha256sum) 486 | 487 | bad_subject = CSRFixture( 488 | orgunit="Example test dept.", 489 | commonname="baz.example.com", 490 | pem=dedent( 491 | """\ 492 | -----BEGIN CERTIFICATE REQUEST----- 493 | MIIBCDCBswIBADBOMRUwEwYDVQQKDAxFeGFtcGxlIGluYy4xGzAZBgNVBAsMEkV4 494 | YW1wbGUgdGVzdCBkZXB0LjEYMBYGA1UEAwwPYmF6LmV4YW1wbGUuY29tMFwwDQYJ 495 | KoZIhvcNAQEBBQADSwAwSAJBAOQ+LeU8pbEg5/XeD+HLnGah4A96qDL4HtNsTW0N 496 | //DbwGchtE8h9LSs3ePXWDVHak87Jx8A+wq7DRUd/LDVP6cCAwEAAaAAMA0GCSqG 497 | SIb3DQEBBQUAA0EAhriivXQYFbdc8QrnDjwVCX8ZGXiGKQEC66LceWDdvOy+mDu8 498 | gi+L6IgnptU8VmEowAPp0veIH1MWJrnGdp7M0g== 499 | -----END CERTIFICATE REQUEST----- 500 | """ 501 | ).encode("utf-8"), 502 | subject_components=( 503 | ("O", "Example inc."), 504 | ("OU", "Example test dept."), 505 | ("CN", "baz.example.com"), 506 | ), 507 | ) 508 | 509 | large_body = CSRFixture( 510 | pem="".join(("foobar", "x" * views._MAXLEN)).encode("utf-8"), 511 | ) 512 | -------------------------------------------------------------------------------- /tests/test_config.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | """tests.test_config contains the unittests for caramel.config""" 4 | import argparse 5 | import logging 6 | import unittest 7 | 8 | from caramel import config 9 | 10 | 11 | class TestConfig(unittest.TestCase): 12 | """Tests for the caramel.config library""" 13 | 14 | def test_inifile_argument(self): 15 | """path as argument, no path in the environment""" 16 | my_ini = "/a/path/to/my_ini_file.ini" 17 | 18 | parser = argparse.ArgumentParser() 19 | config.add_inifile_argument(parser, {}) 20 | args = parser.parse_args([my_ini]) 21 | 22 | self.assertEqual(args.inifile, my_ini) 23 | 24 | def test_inifile_env(self): 25 | """path in the environment, no path argument""" 26 | my_ini = "/a/path/to/my_ini_file.ini" 27 | env = {"CARAMEL_INI": my_ini} 28 | 29 | parser = argparse.ArgumentParser() 30 | config.add_inifile_argument(parser, env) 31 | args = parser.parse_args([]) 32 | 33 | self.assertEqual(args.inifile, my_ini) 34 | 35 | def test_inifile_argument_env(self): 36 | """different paths as argument and in environment, 37 | argument takes priority""" 38 | my_ini = "/a/path/to/my_ini_file.ini" 39 | other_ini = "/a/path/to/other_ini_file.ini" 40 | env = {"CARAMEL_INI": other_ini} 41 | 42 | parser = argparse.ArgumentParser() 43 | config.add_inifile_argument(parser, env) 44 | args = parser.parse_args([my_ini]) 45 | 46 | self.assertEqual(args.inifile, my_ini) 47 | 48 | 49 | class TestGetConfigValue(unittest.TestCase): 50 | """Tests for caramel.config._get_config_value""" 51 | 52 | def test_argument_only(self): 53 | """Test that a value will be returned even without settings or an 54 | env-variable""" 55 | variable_value = "very important configuration detail" 56 | variable_name = "my-var" 57 | arguments = argparse.Namespace() 58 | setattr(arguments, variable_name, variable_value) 59 | value = config._get_config_value(arguments, variable_name, env={}) 60 | self.assertEqual(variable_value, value) 61 | 62 | def test_argument_preferred(self): 63 | """Test to see that argument value is preferred when the variable exists in 64 | settings and environment as well""" 65 | variable_name = "my-var" 66 | arg_value = "The best stuff around" 67 | env_name = "CARAMEL_MY_VAR" 68 | 69 | arguments = argparse.Namespace() 70 | setattr(arguments, variable_name, arg_value) 71 | value = config._get_config_value( 72 | arguments, 73 | variable_name, 74 | settings={variable_name: "The worstest"}, 75 | env={env_name: "The worst stuff"}, 76 | ) 77 | self.assertEqual(arg_value, value) 78 | 79 | def test_env_preferred(self): 80 | """Test to see that env value is preferred when the variable exists in 81 | settings as well""" 82 | variable_name = "my-var" 83 | env_value = "The best stuff around" 84 | env_name = "CARAMEL_MY_VAR" 85 | arguments = argparse.Namespace() 86 | setattr(arguments, variable_name, None) 87 | value = config._get_config_value( 88 | arguments, 89 | variable_name, 90 | settings={variable_name: "The worstest"}, 91 | env={env_name: env_value}, 92 | ) 93 | self.assertEqual(env_value, value) 94 | 95 | def test_settings_only(self): 96 | """Test to see that the value from settings is returned when no argument or 97 | env-variable""" 98 | variable_name = "my-var" 99 | settings_value = "Come on Toshi, you're sooo good" 100 | arguments = argparse.Namespace() 101 | setattr(arguments, variable_name, None) 102 | value = config._get_config_value( 103 | arguments, 104 | variable_name, 105 | settings={variable_name: settings_value}, 106 | env={}, 107 | ) 108 | self.assertEqual(settings_value, value) 109 | 110 | def test_settings_only_no_argument(self): 111 | """Test to see that the value from settings is returned when variable is not 112 | settable from the commandline and no env-variable""" 113 | variable_name = "my-var" 114 | settings_value = "Come on Toshi, you're sooo good" 115 | arguments = argparse.Namespace() 116 | value = config._get_config_value( 117 | arguments, 118 | variable_name, 119 | settings={variable_name: settings_value}, 120 | env={}, 121 | ) 122 | self.assertEqual(settings_value, value) 123 | 124 | def test_different_setting_name_only(self): 125 | """Test to see that the value from settings is returned when the name of the 126 | settings differs from the varaible name""" 127 | variable_name = "my-var" 128 | setting_name = "something.very.different" 129 | settings_value = "Come on Toshi, you're sooo good" 130 | arguments = argparse.Namespace() 131 | setattr(arguments, variable_name, None) 132 | value = config._get_config_value( 133 | arguments, 134 | variable_name, 135 | setting_name=setting_name, 136 | settings={setting_name: settings_value}, 137 | env={}, 138 | ) 139 | self.assertEqual(settings_value, value) 140 | 141 | def test_nothing(self): 142 | """Test to see that if no value has been supplied as either an argument, 143 | environment-variable or setting it returns None""" 144 | variable_name = "my-var" 145 | arguments = argparse.Namespace() 146 | setattr(arguments, variable_name, None) 147 | value = config._get_config_value( 148 | arguments, 149 | variable_name, 150 | settings={}, 151 | env={}, 152 | ) 153 | self.assertEqual(None, value) 154 | 155 | def test_requierd_nothing(self): 156 | """Test to see that if no value has been supplied as either an argument, 157 | environment-variable or setting and the variable is required a ValueError 158 | will be raised""" 159 | variable_name = "my-var" 160 | arguments = argparse.Namespace() 161 | setattr(arguments, variable_name, None) 162 | with self.assertRaises(ValueError): 163 | config._get_config_value( 164 | arguments, 165 | variable_name, 166 | required=True, 167 | settings={}, 168 | env={}, 169 | ) 170 | 171 | 172 | class TestVerbosity(unittest.TestCase): 173 | """Tests for the verbosity configuration from caramel.config""" 174 | 175 | """Data set used for testing config.get_log_level, 176 | (argument_level, environment, root_level, expected)""" 177 | VERBOSITY_DATA: tuple = ( 178 | (2, {}, logging.CRITICAL, logging.INFO), 179 | (-1, {"CARAMEL_LOG_LEVEL": "ERROR"}, logging.CRITICAL, logging.ERROR), 180 | (2, {"CARAMEL_LOG_LEVEL": "WARNING"}, logging.ERROR, logging.INFO), 181 | (2, {"CARAMEL_LOG_LEVEL": "DEBUG"}, logging.WARNING, logging.DEBUG), 182 | (2, {"CARAMEL_LOG_LEVEL": "WARNING"}, logging.DEBUG, logging.DEBUG), 183 | (2, {"CARAMEL_LOG_LEVEL": "DEBUG"}, logging.WARNING, logging.DEBUG), 184 | (0, {"CARAMEL_LOG_LEVEL": "INFO"}, logging.DEBUG, logging.DEBUG), 185 | (0, {"CARAMEL_LOG_LEVEL": "DEBUG"}, logging.WARNING, logging.DEBUG), 186 | ) 187 | 188 | """Data set used for testing config.add_verbosity_argument, 189 | ([arguments], expected)""" 190 | VERBOSITY_ARGUMENT_DATA: tuple = ( 191 | ([], 0), 192 | (["-v"], 1), 193 | (["-vv"], 2), 194 | (["-vvv"], 3), 195 | (["-vvvv"], 4), 196 | (["--verbose", "-v"], 2), 197 | (["--verbose", "-vv"], 3), 198 | (["--verbose", "-v", "--verbose"], 3), 199 | ) 200 | 201 | def test_verbosity_argument(self): 202 | """tests multiple cases for config.add_verbosity_argument""" 203 | 204 | for arg, expected in TestVerbosity.VERBOSITY_ARGUMENT_DATA: 205 | with self.subTest(arg=arg, expected=expected): 206 | parser = argparse.ArgumentParser() 207 | config.add_verbosity_argument(parser) 208 | args = parser.parse_args(arg) 209 | self.assertEqual(expected, args.verbose) 210 | 211 | def test_get_log_level(self): 212 | """tests multiple cases for config.get_log_level""" 213 | logger = logging.getLogger("fake") 214 | 215 | for arg_lvl, env, root_lvl, expected in TestVerbosity.VERBOSITY_DATA: 216 | with self.subTest( 217 | arg_lvl=arg_lvl, env=env, root_lvl=root_lvl, expected=expected 218 | ): 219 | logger.setLevel(root_lvl) 220 | verbosity = config.get_log_level(arg_lvl, logger, env) 221 | self.assertEqual(expected, verbosity) 222 | -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | 4 | import unittest 5 | from operator import attrgetter 6 | 7 | from sqlalchemy.exc import IntegrityError 8 | from sqlalchemy.orm.exc import NoResultFound 9 | 10 | from caramel.models import ( 11 | CSR, 12 | SigningCert, 13 | ) 14 | 15 | from . import ModelTestCase, fixtures 16 | 17 | 18 | class TestCSR(ModelTestCase): 19 | def test_good(self): 20 | csrs = [fixtures.CSRData.initial] 21 | self.assertSimilarSequence(CSR.all(), csrs) 22 | csrs.append(fixtures.CSRData.good) 23 | csrs[-1]().save() 24 | sortkey = attrgetter("sha256sum") 25 | csrs.sort(key=sortkey) 26 | self.assertSimilarSequence(sorted(CSR.all(), key=sortkey), csrs) 27 | self.assertTrue(csrs[1].match(CSR.by_sha256sum(csrs[1].sha256sum))) 28 | 29 | def test_not_found(self): 30 | with self.assertRaises(NoResultFound): 31 | CSR.by_sha256sum(fixtures.CSRData.good.sha256sum) 32 | 33 | def test_not_unique(self): 34 | with self.assertRaises(IntegrityError): 35 | fixtures.CSRData.initial().save() 36 | 37 | def test_bad_signature(self): 38 | with self.assertRaises(ValueError): 39 | fixtures.CSRData.bad_signature().save() 40 | 41 | def test_truncated(self): 42 | with self.assertRaises(ValueError): 43 | fixtures.CSRData.truncated().save() 44 | 45 | def test_trailing_content(self): 46 | with self.assertRaises(ValueError): 47 | fixtures.CSRData.trailing_content().save() 48 | 49 | def test_multi_request(self): 50 | with self.assertRaises(ValueError): 51 | fixtures.CSRData.multi_request().save() 52 | 53 | def test_not_pem(self): 54 | with self.assertRaises(ValueError): 55 | fixtures.CSRData.not_pem().save() 56 | 57 | def test_empty(self): 58 | with self.assertRaises(ValueError): 59 | fixtures.CSRData.empty().save() 60 | 61 | 62 | class TestGetCAPrefix(unittest.TestCase): 63 | def setUp(self): 64 | pass 65 | 66 | def tearDown(self): 67 | pass 68 | 69 | def test_blank_file(self): 70 | import OpenSSL 71 | 72 | with self.assertRaises(OpenSSL.crypto.Error): 73 | SigningCert("") 74 | 75 | def test_valid_cert(self): 76 | ca = SigningCert(fixtures.CertificateData.ca_cert.pem) 77 | ca.get_ca_prefix() 78 | 79 | def test_outdated_cert_should_work(self): 80 | ca = SigningCert(fixtures.CertificateData.expired.pem) 81 | ca.get_ca_prefix() 82 | 83 | def test_empty_returns_from_empty_subject(self): 84 | ca = SigningCert(fixtures.CertificateData.initial.pem) 85 | result = ca.get_ca_prefix() 86 | self.assertEqual((), result) 87 | 88 | def test_empty_returns_from_empty_selector(self): 89 | ca = SigningCert(fixtures.CertificateData.ca_cert.pem) 90 | result = ca.get_ca_prefix(()) 91 | self.assertEqual((), result) 92 | 93 | def test_valid_returns_from_default_subject(self): 94 | ca = SigningCert(fixtures.CertificateData.ca_cert.pem) 95 | r = ca.get_ca_prefix() 96 | self.assertEqual(fixtures.CertificateData.ca_cert.common_subject, r) 97 | 98 | def test_only_CN_returns_from_CN_selector(self): 99 | CN_TUPLE = (("CN", "Caramel Signing Certificate"),) 100 | ca = SigningCert(fixtures.CertificateData.ca_cert.pem) 101 | result = ca.get_ca_prefix((b"CN",)) 102 | self.assertEqual(CN_TUPLE, result) 103 | 104 | def test_only_wanted_returns_from_selector(self): 105 | SELECTED = ( 106 | ("ST", "Östergötland"), 107 | ("L", "Norrköping"), 108 | ("OU", "Muppar Teknik"), 109 | ) 110 | SELECTOR = (b"ST", b"L", b"OU") 111 | ca = SigningCert(fixtures.CertificateData.ca_cert.pem) 112 | result = ca.get_ca_prefix(SELECTOR) 113 | self.assertEqual(SELECTED, result) 114 | 115 | 116 | class TestQuery(ModelTestCase): 117 | def test_list_items(self): 118 | """initial is signed, good is unsigned""" 119 | initial = fixtures.CSRData.initial 120 | good = fixtures.CSRData.good() 121 | good.save() 122 | expected = [ 123 | ( 124 | 1, 125 | initial.commonname, 126 | initial.sha256sum, 127 | initial.certificates[-1].not_after, 128 | ), 129 | (2, good.commonname, good.sha256sum, None), 130 | ] 131 | self.assertEqual(CSR.list_csr_printable(), expected) 132 | 133 | def test_refreshable(self): 134 | """Good is not signed and should not be refreshable""" 135 | fixtures.CSRData.good().save() 136 | expected = [fixtures.CSRData.initial] 137 | self.assertSimilarSequence(CSR.refreshable(), expected) 138 | 139 | def test_unsigned(self): 140 | """Good is not signed and should be the only one""" 141 | good = fixtures.CSRData.good() 142 | good.save() 143 | self.assertSimilarSequence(CSR.unsigned(), [good]) 144 | -------------------------------------------------------------------------------- /tests/test_views.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : 3 | import datetime 4 | import unittest 5 | import unittest.mock 6 | 7 | from pyramid import testing 8 | from pyramid.httpexceptions import ( 9 | HTTPBadRequest, 10 | HTTPLengthRequired, 11 | HTTPNotFound, 12 | HTTPRequestEntityTooLarge, 13 | ) 14 | from pyramid.response import Response 15 | 16 | from caramel import views 17 | from caramel.models import ( 18 | CSR, 19 | AccessLog, 20 | ) 21 | 22 | from . import ModelTestCase, fixtures 23 | 24 | 25 | def dummypost(fix, **args): 26 | req = testing.DummyRequest(**args) 27 | req.body = fix.pem 28 | req.content_length = len(req.body) 29 | req.matchdict["sha256"] = fix.sha256sum 30 | req.registry.settings["ca.cert"] = "abc123.crt" 31 | return req 32 | 33 | 34 | class TestCSRAdd(ModelTestCase): 35 | def setUp(self): 36 | super(TestCSRAdd, self).setUp() 37 | self.config = testing.setUp() 38 | # Store original 39 | self._from_files = views.SigningCert.from_files 40 | 41 | # mock instance that returns value 42 | _mocking = unittest.mock.Mock() 43 | _mocking.get_ca_prefix.return_value = fixtures.subject_prefix 44 | 45 | # Mock the object initializer 46 | views.SigningCert.from_files = unittest.mock.Mock() 47 | views.SigningCert.from_files.return_value = _mocking 48 | 49 | def tearDown(self): 50 | super(TestCSRAdd, self).tearDown() 51 | testing.tearDown() 52 | views.SigningCert.from_files = self._from_files 53 | 54 | def test_good(self): 55 | req = dummypost(fixtures.CSRData.good) 56 | csr = views.csr_add(req) 57 | self.assertSimilar(fixtures.CSRData.good, csr) 58 | 59 | def test_duplicate(self): 60 | req = dummypost(fixtures.CSRData.initial) 61 | with self.assertRaises(HTTPBadRequest): 62 | views.csr_add(req) 63 | 64 | def test_no_length(self): 65 | req = dummypost(fixtures.CSRData.good) 66 | req.content_length = None 67 | with self.assertRaises(HTTPLengthRequired): 68 | views.csr_add(req) 69 | 70 | def test_large(self): 71 | req = dummypost(fixtures.CSRData.large_body) 72 | with self.assertRaises(HTTPRequestEntityTooLarge): 73 | views.csr_add(req) 74 | 75 | def test_empty(self): 76 | req = dummypost(fixtures.CSRData.empty) 77 | with self.assertRaises(HTTPBadRequest): 78 | views.csr_add(req) 79 | 80 | def test_not_pem(self): 81 | req = dummypost(fixtures.CSRData.not_pem) 82 | with self.assertRaises(HTTPBadRequest): 83 | views.csr_add(req) 84 | 85 | def test_trailing_junk(self): 86 | req = dummypost(fixtures.CSRData.trailing_content) 87 | with self.assertRaises(HTTPBadRequest): 88 | views.csr_add(req) 89 | 90 | def test_leading_junk(self): 91 | req = dummypost(fixtures.CSRData.leading_content) 92 | with self.assertRaises(HTTPBadRequest): 93 | views.csr_add(req) 94 | 95 | def test_multi_pem(self): 96 | req = dummypost(fixtures.CSRData.multi_request) 97 | with self.assertRaises(HTTPBadRequest): 98 | views.csr_add(req) 99 | 100 | def test_bad_signature(self): 101 | req = dummypost(fixtures.CSRData.bad_signature) 102 | with self.assertRaises(HTTPBadRequest): 103 | views.csr_add(req) 104 | 105 | def test_bad_checksum(self): 106 | req = dummypost(fixtures.CSRData.bad_sha) 107 | with self.assertRaises(HTTPBadRequest): 108 | views.csr_add(req) 109 | 110 | def test_bad_subject(self): 111 | req = dummypost(fixtures.CSRData.bad_subject) 112 | with self.assertRaises(HTTPBadRequest): 113 | views.csr_add(req) 114 | 115 | 116 | class TestCertFetch(ModelTestCase): 117 | def setUp(self): 118 | super(TestCertFetch, self).setUp() 119 | self.config = testing.setUp() 120 | self.req = testing.DummyRequest() 121 | self.req.remote_addr = "test" 122 | # TODO: ... 123 | 124 | def tearDown(self): 125 | super(TestCertFetch, self).tearDown() 126 | testing.tearDown() 127 | # TODO: ... 128 | 129 | def test_missing(self): 130 | self.req.matchdict["sha256"] = fixtures.CSRData.good.sha256sum 131 | accesses = len(AccessLog.all()) 132 | with self.assertRaises(HTTPNotFound): 133 | views.cert_fetch(self.req) 134 | self.assertEqual(accesses, len(AccessLog.all())) 135 | 136 | def test_exists_valid(self): 137 | sha256sum = fixtures.CSRData.initial.sha256sum 138 | csr = CSR.by_sha256sum(sha256sum) 139 | now = datetime.datetime.utcnow() 140 | self.req.matchdict["sha256"] = sha256sum 141 | resp = views.cert_fetch(self.req) 142 | # Verify response contents 143 | self.assertIsInstance(resp, Response) 144 | self.assertEqual(resp.body, csr.certificates[0].pem) 145 | self.assertEqual(self.req.response.status_int, 200) 146 | # Verify there's a new AccessLog entry 147 | self.assertEqual(csr.accessed[0].addr, self.req.remote_addr) 148 | self.assertAlmostEqual( 149 | csr.accessed[0].when, now, delta=datetime.timedelta(seconds=1) 150 | ) 151 | 152 | def test_exists_expired(self): 153 | csr = fixtures.CSRData.with_expired_cert() 154 | csr.save() 155 | now = datetime.datetime.utcnow() 156 | self.req.matchdict["sha256"] = csr.sha256sum 157 | resp = views.cert_fetch(self.req) 158 | # Verify response contents 159 | self.assertIs(resp, csr) 160 | self.assertEqual(self.req.response.status_int, 202) 161 | # Verify there's a new AccessLog entry 162 | self.assertEqual(csr.accessed[0].addr, self.req.remote_addr) 163 | self.assertAlmostEqual( 164 | csr.accessed[0].when, now, delta=datetime.timedelta(seconds=1) 165 | ) 166 | 167 | def test_not_signed(self): 168 | csr = fixtures.CSRData.good() 169 | csr.save() 170 | now = datetime.datetime.utcnow() 171 | self.req.matchdict["sha256"] = csr.sha256sum 172 | resp = views.cert_fetch(self.req) 173 | # Verify response contents 174 | self.assertIs(resp, csr) 175 | self.assertEqual(self.req.response.status_int, 202) 176 | # Verify there's a new AccessLog entry 177 | self.assertEqual(csr.accessed[0].addr, self.req.remote_addr) 178 | self.assertAlmostEqual( 179 | csr.accessed[0].when, now, delta=datetime.timedelta(seconds=1) 180 | ) 181 | pass 182 | --------------------------------------------------------------------------------