├── .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 |
21 |
22 |
23 |
24 |
25 |
26 | Welcome to ${project}, an application generated by
27 | the Pyramid web application development framework.
28 |