summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTom Cammann <tom.cammann@hp.com>2015-03-02 14:11:09 +0000
committerTom Cammann <tom.cammann@hp.com>2015-03-02 14:24:23 +0000
commit4bd60c6a4119b0191bcf7065aedd60c705c95cf2 (patch)
tree4f56ee615380781d41f0731e2de1426d4d2f910a
inital commit for github
-rw-r--r--.gitignore17
-rw-r--r--.test.conf4
-rw-r--r--LICENSE.txt202
-rw-r--r--README.rst108
-rw-r--r--cathead/__init__.py0
-rw-r--r--cathead/cadriver.py23
-rw-r--r--cathead/cathead.py126
-rw-r--r--cathead/certwatch.py100
-rw-r--r--cathead/drivers/__init__.py0
-rw-r--r--cathead/drivers/eca.py58
-rw-r--r--cathead/drivers/selfsign.py30
-rw-r--r--cathead/scheduler.py82
-rw-r--r--cathead/x509.py61
-rw-r--r--example_config.py58
-rw-r--r--requirements.txt3
-rw-r--r--setup.cfg36
-rw-r--r--setup.py30
-rw-r--r--test-requirements.txt6
-rw-r--r--tests/__init__.py0
-rw-r--r--tests/test_cathead.py9
-rw-r--r--tests/test_certwatcher.py50
-rw-r--r--tests/test_ecadriver.py11
-rw-r--r--tests/test_selfsigndriver.py23
-rw-r--r--tests/test_x509.py48
-rw-r--r--tests/util.py0
-rw-r--r--tox.ini28
26 files changed, 1113 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0998c16
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,17 @@
1AUTHORS
2ChangeLog
3*~
4*.swp
5*.pyc
6*.log
7.tox
8.coverage
9cathead.egg-info/
10build/
11doc/build/
12doc/source/api/
13dist/
14.testrepository/
15.project
16.pydevproject
17.venv
diff --git a/.test.conf b/.test.conf
new file mode 100644
index 0000000..1641f86
--- /dev/null
+++ b/.test.conf
@@ -0,0 +1,4 @@
1[DEFAULT]
2test_command=OS_STDOUT_CAPTURE=1 OS_STDERR_CAPTURE=1 OS_TEST_TIMEOUT=60 ${PYTHON:-python} -m subunit.run discover -t ./ . $LISTOPT $IDOPTION
3test_id_option=--load-list $IDFILE
4test_list_option=--list
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..8f71f43
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,202 @@
1 Apache License
2 Version 2.0, January 2004
3 http://www.apache.org/licenses/
4
5 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
7 1. Definitions.
8
9 "License" shall mean the terms and conditions for use, reproduction,
10 and distribution as defined by Sections 1 through 9 of this document.
11
12 "Licensor" shall mean the copyright owner or entity authorized by
13 the copyright owner that is granting the License.
14
15 "Legal Entity" shall mean the union of the acting entity and all
16 other entities that control, are controlled by, or are under common
17 control with that entity. For the purposes of this definition,
18 "control" means (i) the power, direct or indirect, to cause the
19 direction or management of such entity, whether by contract or
20 otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 outstanding shares, or (iii) beneficial ownership of such entity.
22
23 "You" (or "Your") shall mean an individual or Legal Entity
24 exercising permissions granted by this License.
25
26 "Source" form shall mean the preferred form for making modifications,
27 including but not limited to software source code, documentation
28 source, and configuration files.
29
30 "Object" form shall mean any form resulting from mechanical
31 transformation or translation of a Source form, including but
32 not limited to compiled object code, generated documentation,
33 and conversions to other media types.
34
35 "Work" shall mean the work of authorship, whether in Source or
36 Object form, made available under the License, as indicated by a
37 copyright notice that is included in or attached to the work
38 (an example is provided in the Appendix below).
39
40 "Derivative Works" shall mean any work, whether in Source or Object
41 form, that is based on (or derived from) the Work and for which the
42 editorial revisions, annotations, elaborations, or other modifications
43 represent, as a whole, an original work of authorship. For the purposes
44 of this License, Derivative Works shall not include works that remain
45 separable from, or merely link (or bind by name) to the interfaces of,
46 the Work and Derivative Works thereof.
47
48 "Contribution" shall mean any work of authorship, including
49 the original version of the Work and any modifications or additions
50 to that Work or Derivative Works thereof, that is intentionally
51 submitted to Licensor for inclusion in the Work by the copyright owner
52 or by an individual or Legal Entity authorized to submit on behalf of
53 the copyright owner. For the purposes of this definition, "submitted"
54 means any form of electronic, verbal, or written communication sent
55 to the Licensor or its representatives, including but not limited to
56 communication on electronic mailing lists, source code control systems,
57 and issue tracking systems that are managed by, or on behalf of, the
58 Licensor for the purpose of discussing and improving the Work, but
59 excluding communication that is conspicuously marked or otherwise
60 designated in writing by the copyright owner as "Not a Contribution."
61
62 "Contributor" shall mean Licensor and any individual or Legal Entity
63 on behalf of whom a Contribution has been received by Licensor and
64 subsequently incorporated within the Work.
65
66 2. Grant of Copyright License. Subject to the terms and conditions of
67 this License, each Contributor hereby grants to You a perpetual,
68 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 copyright license to reproduce, prepare Derivative Works of,
70 publicly display, publicly perform, sublicense, and distribute the
71 Work and such Derivative Works in Source or Object form.
72
73 3. Grant of Patent License. Subject to the terms and conditions of
74 this License, each Contributor hereby grants to You a perpetual,
75 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 (except as stated in this section) patent license to make, have made,
77 use, offer to sell, sell, import, and otherwise transfer the Work,
78 where such license applies only to those patent claims licensable
79 by such Contributor that are necessarily infringed by their
80 Contribution(s) alone or by combination of their Contribution(s)
81 with the Work to which such Contribution(s) was submitted. If You
82 institute patent litigation against any entity (including a
83 cross-claim or counterclaim in a lawsuit) alleging that the Work
84 or a Contribution incorporated within the Work constitutes direct
85 or contributory patent infringement, then any patent licenses
86 granted to You under this License for that Work shall terminate
87 as of the date such litigation is filed.
88
89 4. Redistribution. You may reproduce and distribute copies of the
90 Work or Derivative Works thereof in any medium, with or without
91 modifications, and in Source or Object form, provided that You
92 meet the following conditions:
93
94 (a) You must give any other recipients of the Work or
95 Derivative Works a copy of this License; and
96
97 (b) You must cause any modified files to carry prominent notices
98 stating that You changed the files; and
99
100 (c) You must retain, in the Source form of any Derivative Works
101 that You distribute, all copyright, patent, trademark, and
102 attribution notices from the Source form of the Work,
103 excluding those notices that do not pertain to any part of
104 the Derivative Works; and
105
106 (d) If the Work includes a "NOTICE" text file as part of its
107 distribution, then any Derivative Works that You distribute must
108 include a readable copy of the attribution notices contained
109 within such NOTICE file, excluding those notices that do not
110 pertain to any part of the Derivative Works, in at least one
111 of the following places: within a NOTICE text file distributed
112 as part of the Derivative Works; within the Source form or
113 documentation, if provided along with the Derivative Works; or,
114 within a display generated by the Derivative Works, if and
115 wherever such third-party notices normally appear. The contents
116 of the NOTICE file are for informational purposes only and
117 do not modify the License. You may add Your own attribution
118 notices within Derivative Works that You distribute, alongside
119 or as an addendum to the NOTICE text from the Work, provided
120 that such additional attribution notices cannot be construed
121 as modifying the License.
122
123 You may add Your own copyright statement to Your modifications and
124 may provide additional or different license terms and conditions
125 for use, reproduction, or distribution of Your modifications, or
126 for any such Derivative Works as a whole, provided Your use,
127 reproduction, and distribution of the Work otherwise complies with
128 the conditions stated in this License.
129
130 5. Submission of Contributions. Unless You explicitly state otherwise,
131 any Contribution intentionally submitted for inclusion in the Work
132 by You to the Licensor shall be under the terms and conditions of
133 this License, without any additional terms or conditions.
134 Notwithstanding the above, nothing herein shall supersede or modify
135 the terms of any separate license agreement you may have executed
136 with Licensor regarding such Contributions.
137
138 6. Trademarks. This License does not grant permission to use the trade
139 names, trademarks, service marks, or product names of the Licensor,
140 except as required for reasonable and customary use in describing the
141 origin of the Work and reproducing the content of the NOTICE file.
142
143 7. Disclaimer of Warranty. Unless required by applicable law or
144 agreed to in writing, Licensor provides the Work (and each
145 Contributor provides its Contributions) on an "AS IS" BASIS,
146 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 implied, including, without limitation, any warranties or conditions
148 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 PARTICULAR PURPOSE. You are solely responsible for determining the
150 appropriateness of using or redistributing the Work and assume any
151 risks associated with Your exercise of permissions under this License.
152
153 8. Limitation of Liability. In no event and under no legal theory,
154 whether in tort (including negligence), contract, or otherwise,
155 unless required by applicable law (such as deliberate and grossly
156 negligent acts) or agreed to in writing, shall any Contributor be
157 liable to You for damages, including any direct, indirect, special,
158 incidental, or consequential damages of any character arising as a
159 result of this License or out of the use or inability to use the
160 Work (including but not limited to damages for loss of goodwill,
161 work stoppage, computer failure or malfunction, or any and all
162 other commercial damages or losses), even if such Contributor
163 has been advised of the possibility of such damages.
164
165 9. Accepting Warranty or Additional Liability. While redistributing
166 the Work or Derivative Works thereof, You may choose to offer,
167 and charge a fee for, acceptance of support, warranty, indemnity,
168 or other liability obligations and/or rights consistent with this
169 License. However, in accepting such obligations, You may act only
170 on Your own behalf and on Your sole responsibility, not on behalf
171 of any other Contributor, and only if You agree to indemnify,
172 defend, and hold each Contributor harmless for any liability
173 incurred by, or claims asserted against, such Contributor by reason
174 of your accepting any such warranty or additional liability.
175
176 END OF TERMS AND CONDITIONS
177
178 APPENDIX: How to apply the Apache License to your work.
179
180 To apply the Apache License to your work, attach the following
181 boilerplate notice, with the fields enclosed by brackets "{}"
182 replaced with your own identifying information. (Don't include
183 the brackets!) The text should be enclosed in the appropriate
184 comment syntax for the file format. We also recommend that a
185 file or class name and description of purpose be included on the
186 same "printed page" as the copyright notice for easier
187 identification within third-party archives.
188
189 Copyright {yyyy} {name of copyright owner}
190
191 Licensed under the Apache License, Version 2.0 (the "License");
192 you may not use this file except in compliance with the License.
193 You may obtain a copy of the License at
194
195 http://www.apache.org/licenses/LICENSE-2.0
196
197 Unless required by applicable law or agreed to in writing, software
198 distributed under the License is distributed on an "AS IS" BASIS,
199 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 See the License for the specific language governing permissions and
201 limitations under the License.
202
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..10c68ad
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,108 @@
1=======
2Cathead
3=======
4
5Cathead is a utility to monitor SSL certificates for expiry and retrieve new
6certificates when expiry is near.
7
8This project is borne out of frustration with using cron and certmonger and
9various other bits of bash to monitor and renew certificates.
10
11.. WARNING::
12This project is under active development so expect changes to APIs and
13configurations.
14
15Running
16"""""""
171. Clone repo ::
18
19 git clone https://github.com/takac/cathead
20
212. Install requirements and cathead into a virtual env. ::
22
23 virtualenv .venv
24 pip install -r requirements.txt
25 pip install .
26
273. Construct a config file specifying which certs to track and how to refresh
28 them. See the `example_config.py <example_config.py>`_ file.
29
30 The *certs* section contains the details of the certificates to monitor and
31 which driver should be used. The common name and other cert details should
32 also be specified here.
33
34 driver
35 Name of the driver to use. Use the name value from the driver.
36
37 key
38 Path to the key. This key will be regenerated at every refresh.
39
40 cert
41 Path to the cert.
42
43 common_name
44 Common name of the certificate.
45
46 on_refresh_success
47 Callback action to execute on successful refresh of cert. Use the name
48 value of an action defined in the actions section.
49
50 on_refresh_failure
51 Callback action to execute on failure to refresh the cert. Use the name
52 value of an action defined in the actions section.
53
54 The *drivers* section specifies how new certs are obtained, the only 2
55 drivers currently supported are Anchor (currently named ECA, due to be
56 changed), and self signed certs.
57
58 name
59 Name of the driver used to associate with certificates.
60
61 driver
62 Python class of the driver. e.g. ``cathead.drivers.selfsign.SelfSignDriver``.
63
64 All other keys in the driver are passed into the driver class at
65 construction. e.g. ``SelfSignDriver(**drivers['selfsign'])``
66
67 The *actions* section contains actions to perform on different events. So
68 far the possible events are:
69
70 - Successful refresh of a certificate
71 - Failure to refresh a certificate
72
73 Actions can either by system calls or python calls.
74
75 name
76 Name of the action, used to associate with a certificate event callback.
77
78 type
79 The type of action, either ``'system'`` for a system call (e.g. ``reboot``)
80 or ``'python'`` which allows executing a python callable.
81
82 module
83 Use this when using type of ``python`` to select which module the
84 callable is in.
85
86 command
87 Specify the command or callable to be run.
88
89 args
90 Specify the arguments to the command or callable. This should be a list.
91
924. Run cathead with your requirements file. ::
93
94 cathead example_config.py
95
96.. NOTE::
97For the self signing driver you will need to generate a key to sign the certs
98with. This can be done using ::
99
100 openssl genrsa 2048 > ca.key
101
102Naming
103""""""
104
105The name comes from the `anchor support
106<https://en.wikipedia.org/wiki/Cathead>`_ as this project can be used in
107conjunction with `Anchor <https://github.com/stackforge/anchor/>`_ an an
108ephemeral PKI service.
diff --git a/cathead/__init__.py b/cathead/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/cathead/__init__.py
diff --git a/cathead/cadriver.py b/cathead/cadriver.py
new file mode 100644
index 0000000..578ff04
--- /dev/null
+++ b/cathead/cadriver.py
@@ -0,0 +1,23 @@
1# Copyright 2015 Tom Cammann
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import abc
17
18
19class CaDriver(object):
20
21 @abc.abstractmethod
22 def sign(self, csr):
23 pass
diff --git a/cathead/cathead.py b/cathead/cathead.py
new file mode 100644
index 0000000..c521278
--- /dev/null
+++ b/cathead/cathead.py
@@ -0,0 +1,126 @@
1# Copyright 2015 Tom Cammann
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import imp
17import importlib
18import logging
19import sys
20
21from oslo_concurrency import processutils
22
23import scheduler
24
25
26class Cathead(object):
27
28 def __init__(self, config):
29 self.config = config
30
31 def start(self):
32 self.setup_logging()
33 self.parse_config()
34 self.wait()
35
36 def setup_logging(self):
37 ch = logging.StreamHandler()
38 logger = logging.getLogger()
39 logger.setLevel(logging.DEBUG)
40 logger.addHandler(ch)
41
42 def extract_drivers(self):
43 drivers = {}
44 for driver in self.config['drivers']:
45 split = driver.pop('driver').split('.')
46 module = importlib.import_module('.'.join(split[:-1]))
47 name = driver.pop('name')
48 drivers[name] = getattr(module, split[-1])(**driver)
49 return drivers
50
51 def parse_config(self):
52
53 drivers = self.extract_drivers()
54 actions = self.extract_actions()
55
56 self._scheduler = scheduler.Scheduler()
57
58 for cert in self.config['certs']:
59 callback = self.create_cert_callback(cert['on_refresh_success'],
60 actions)
61
62 scheduler_conf = {
63 'driver': drivers[cert['driver']],
64 'key_path': cert['key'],
65 'cert_path': cert['cert'],
66 'refresh_window': cert['refresh_window'],
67 'common_name': cert['common_name'],
68 'on_refresh_success': callback,
69 'jitter': 0,
70 }
71
72 self._scheduler.add_cert_watch(**scheduler_conf)
73
74 return self._scheduler
75
76 def extract_actions(self):
77 actions = {}
78 for action in self.config['actions']:
79 if action['type'] == 'python':
80
81 def create_closure():
82 closure = action
83
84 def callback():
85 module = importlib.import_module(closure['module'])
86 getattr(module, closure['command'])(*closure['args'])
87 return callback
88 actions[action['name']] = create_closure()
89 elif action['type'] == 'system':
90 # closure = action.copy()
91
92 def create_closure():
93 closure = action
94
95 def callback():
96 command = [closure['command']]
97 command.extend(closure['args']
98 if closure['args'] else [])
99 processutils.execute(*command)
100 return callback
101 actions[action['name']] = create_closure()
102 return actions
103
104 def create_cert_callback(self, action, actions):
105 def callback():
106 on_success = action
107 if isinstance(on_success, str):
108 actions[on_success]()
109 else:
110 for func in on_success:
111 actions[func]()
112 return callback
113
114 def wait(self):
115 self._scheduler.wait()
116
117def main():
118 if len(sys.argv) == 2:
119 # sys.path.append(os.path.abspath(sys.argv[1]))
120 # conf_module = importlib.import_module(sys.argv[1].split(".py")[0])
121 # conf = __import__(sys.argv[1].split(".py")[0])
122 (file, path, desc) = imp.find_module(sys.argv[1].split(".py")[0], ["."])
123 conf_module = imp.load_module('', file, path, desc)
124 Cathead(conf_module.CONF).start()
125 else:
126 print("Usage: cathead path/to/configy.py")
diff --git a/cathead/certwatch.py b/cathead/certwatch.py
new file mode 100644
index 0000000..bd44b29
--- /dev/null
+++ b/cathead/certwatch.py
@@ -0,0 +1,100 @@
1# Copyright 2015 Tom Cammann
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import datetime
17import logging
18import os.path
19
20import x509
21
22LOG = logging.getLogger(__name__)
23
24
25class CertWatcher(object):
26
27 def __init__(self, key_path, cert_path, common_name, ca_driver,
28 on_refresh_success=None, on_refresh_failure=None,
29 refresh_window=None):
30 if not os.path.isfile(key_path):
31 raise Exception("key needs to exist")
32 self.key_path = key_path
33 self.cert_path = cert_path
34 self.ca_driver = ca_driver
35 self.on_refresh_success = on_refresh_success
36 self.on_refresh_failure = on_refresh_failure
37 self.common_name = common_name
38 self.refresh_window = refresh_window
39
40 @property
41 def key(self):
42 return open(self.key_path).read()
43
44 @property
45 def cert(self):
46 return open(self.cert_path).read()
47
48 def get_expire_date(self):
49 return x509.get_expire_date(self.cert)
50
51 def seconds_until_expiry(self):
52 diff = self.get_expire_date() - datetime.datetime.now()
53 return diff.total_seconds()
54
55 def _replace_cert(self, cert_contents):
56 LOG.info("Replacing certificate at %s" % self.cert_path)
57 cert = open(self.cert_path, "w")
58 cert.write(cert_contents)
59 cert.close()
60
61 def _will_be_expired(self, date):
62 return date > self.get_expire_date()
63
64 def _expires_in_window(self):
65 now = datetime.datetime.now()
66 if not self.refresh_window:
67 LOG.debug("No refresh window set, assuming expired")
68 return True
69 window = now + datetime.timedelta(0, self.refresh_window)
70 if self._will_be_expired(window):
71 LOG.info("%s is expired inside window of %s"
72 % (self.cert_path, self.refresh_window))
73 return True
74 LOG.info("Certificate valid within window of %s seconds"
75 % self.refresh_window)
76 return False
77
78 def _cert_exists(self):
79 if not os.path.isfile(self.cert_path):
80 LOG.info("No cert found at %s" % self.cert_path)
81 return False
82 return True
83
84 def is_invalid_cert(self):
85 return not self._cert_exists() or self._expires_in_window()
86
87 def check_and_update(self):
88 LOG.info('Checking validity of certificate %s' % self.cert_path)
89 if self.is_invalid_cert():
90 csr = x509.generate_csr(self.key, self.common_name)
91 cert = None
92 try:
93 cert = self.ca_driver.sign(csr)
94 except Exception as e:
95 LOG.exception("Could not retrieve cert\n%s", e)
96 if cert:
97 self._replace_cert(cert)
98 self.on_refresh_success()
99 else:
100 self.on_refresh_failure()
diff --git a/cathead/drivers/__init__.py b/cathead/drivers/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/cathead/drivers/__init__.py
diff --git a/cathead/drivers/eca.py b/cathead/drivers/eca.py
new file mode 100644
index 0000000..710f661
--- /dev/null
+++ b/cathead/drivers/eca.py
@@ -0,0 +1,58 @@
1# Copyright 2015 Tom Cammann
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import datetime
17import logging
18
19import requests
20
21from cathead import cadriver
22from cathead import x509
23
24LOG = logging.getLogger(__name__)
25
26
27class EcaDriver(cadriver.CaDriver):
28
29 def __init__(self, host, port,
30 user, secret, scheme='http'):
31 self.host = host
32 self.port = port
33 self.user = user
34 self.secret = secret
35 self.scheme = scheme
36
37 def sign(self, csr):
38 url = "{scheme}://{host}:{port}/sign".format(**self.__dict__)
39 LOG.info("Sending CSR to %s" % url)
40 params = {"user": self.user,
41 "secret": self.secret,
42 "encoding": "pem",
43 "csr": csr}
44 r = requests.post(url, data=params)
45 cert = r.text
46 LOG.debug("Received from ECA server:\n%s" % cert)
47 if self._is_valid_cert(cert):
48 return cert
49 else:
50 LOG.info("Received invalid certificate from ECA")
51
52 def _is_valid_cert(self, cert):
53 try:
54 expire = x509.get_expire_date(cert)
55 return expire > datetime.datetime.now()
56 except Exception as e:
57 LOG.info("invalid cert, failed check date with:\n%s", e)
58 return False
diff --git a/cathead/drivers/selfsign.py b/cathead/drivers/selfsign.py
new file mode 100644
index 0000000..50c60f1
--- /dev/null
+++ b/cathead/drivers/selfsign.py
@@ -0,0 +1,30 @@
1# Copyright 2015 Tom Cammann
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import os.path
17
18from cathead import cadriver
19from cathead import x509
20
21
22class SelfSignDriver(cadriver.CaDriver):
23
24 def __init__(self, ca_key_file, check_key_file=True):
25 if check_key_file and not os.path.isfile(ca_key_file):
26 raise Exception("Key %s not found" % ca_key_file)
27 self.ca_key_file = ca_key_file
28
29 def sign(self, csr):
30 return x509.generate_cert(open(self.ca_key_file).read(), csr)
diff --git a/cathead/scheduler.py b/cathead/scheduler.py
new file mode 100644
index 0000000..fcffd44
--- /dev/null
+++ b/cathead/scheduler.py
@@ -0,0 +1,82 @@
1# Copyright 2015 Tom Cammann
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import logging
17
18from apscheduler.jobstores.base import JobLookupError
19from apscheduler.schedulers import background
20
21import certwatch
22
23LOG = logging.getLogger(__name__)
24
25
26class Scheduler(object):
27
28 def __init__(self):
29 self._scheduler = background.BackgroundScheduler()
30 self._scheduler.configure(daemon=True)
31 self.job_dict = {}
32 self._scheduler.start()
33
34 def is_tracked(self, key_path):
35 return key_path in self.job_dict
36
37 def _remove_job(self, key_path):
38 try:
39 self._scheduler.remove_job(key_path)
40 except JobLookupError:
41 LOG.info("No scheduled job for %s, creating new job", key_path)
42
43 def _create_success_callback(self, key_path, callback):
44 def success_callback():
45 job_info = self.job_dict[key_path]
46 self._remove_job(key_path)
47 watcher = job_info['watcher']
48 seconds = watcher.seconds_until_expiry()
49 new_interval = seconds - seconds / 5
50 self._scheduler.add_job(watcher.check_and_update, 'interval',
51 seconds=new_interval, id=key_path)
52 if callback:
53 callback()
54 return success_callback
55
56 def _create_failure_callback(self, key_path):
57 def failure_callback():
58 job_info = self.job_dict[key_path]
59 self._remove_job(key_path)
60 watcher = job_info['watcher']
61 self._scheduler.add_job(watcher.check_and_update,
62 'interval', seconds=10, id=key_path)
63 return failure_callback
64
65 def add_cert_watch(self, driver, key_path, cert_path,
66 common_name, on_refresh_success=None,
67 jitter=0, refresh_window=None):
68 if self.is_tracked(key_path):
69 raise Exception("Already tracking certificate")
70
71 on_success = self._create_success_callback(key_path,
72 on_refresh_success)
73 on_failure = on_failure = self._create_failure_callback(key_path)
74 watcher = certwatch.CertWatcher(key_path, cert_path, common_name,
75 driver, on_refresh_success=on_success,
76 on_refresh_failure=on_failure)
77
78 self.job_dict[key_path] = {'watcher': watcher}
79 watcher.check_and_update()
80
81 def wait(self):
82 self._scheduler._thread.join()
diff --git a/cathead/x509.py b/cathead/x509.py
new file mode 100644
index 0000000..2315ca2
--- /dev/null
+++ b/cathead/x509.py
@@ -0,0 +1,61 @@
1# Copyright 2015 Tom Cammann
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import datetime
17import logging
18import tempfile
19
20from oslo_concurrency import processutils
21
22LOG = logging.getLogger(__name__)
23
24
25def generate_key():
26 return processutils.execute("openssl", "genrsa", "2048")[0]
27
28
29def generate_cert(key, csr):
30 key_file = _create_temp_file(key)
31 csr_file = _create_temp_file(csr)
32 return processutils.execute("openssl", "x509", "-req", "-days",
33 "365", "-in", csr_file.name, "-signkey",
34 key_file.name)[0]
35
36
37def get_expire_date(cert):
38 # open cert with openssl and parse
39 cert_file = _create_temp_file(cert)
40 out = processutils.execute("openssl", "x509", "-in", cert_file.name,
41 "-dates", "-issuer", "-noout", "-subject")
42 strdate = out[0].split("\n")[1].split("=")[1]
43 return datetime.datetime.strptime(strdate, "%b %d %H:%M:%S %Y %Z")
44
45
46def generate_csr(key, common_name,
47 country="", organisation=""):
48 LOG.debug("Generating CSR")
49 key_file = _create_temp_file(key)
50 out = processutils.execute("openssl", "req", "-new", "-key", key_file.name,
51 "-subj",
52 "/C=%s/O=%s/CN=%s" %
53 (country, organisation, common_name))
54 return out[0]
55
56
57def _create_temp_file(contents):
58 temp_file = tempfile.NamedTemporaryFile()
59 temp_file.file.write(contents)
60 temp_file.flush()
61 return temp_file
diff --git a/example_config.py b/example_config.py
new file mode 100644
index 0000000..4e123bc
--- /dev/null
+++ b/example_config.py
@@ -0,0 +1,58 @@
1# Copyright 2015 Tom Cammann
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16CONF = {
17 'failure_refresh_timeout': 10,
18 'drivers': [
19 {
20 'name': 'selfsign',
21 'driver': 'cathead.drivers.selfsign.SelfSignDriver',
22 'ca_key': 'ca.p.key',
23 },
24 {
25 'name': 'eca',
26 'driver': 'cathead.drivers.eca.EcaDriver',
27 'host': '127.0.0.1',
28 'port': 5000,
29 'user': 'woot',
30 'secret': 'woot',
31 }
32 ],
33 'certs': [
34 {
35 'driver': 'eca',
36 'key': 'ca.p.key',
37 'cert': 'newcrt.crt',
38 'refresh_window': None,
39 'common_name': '127.0.0.1',
40 'on_refresh_success': 'hello_system',
41 }
42 ],
43 'actions': [
44 {
45 'name': 'hello_python',
46 'type': 'python',
47 'module': 'os',
48 'command': 'write',
49 'args': [2, 'hello world'],
50 },
51 {
52 'name': 'hello_system',
53 'type': 'system',
54 'command': 'echo',
55 'args': ['hello echo world'],
56 },
57 ]
58}
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..b242a77
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,3 @@
1apscheduler
2oslo.concurrency
3requests
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..20a773d
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,36 @@
1[metadata]
2name = cathead
3author = Tom Cammann
4author-email = tom.cammann@hp.com
5summary = Certificate monitoring service
6description-file =
7 README.rst
8home-page = None
9classifier =
10 Development Status :: 4 - Beta
11 Environment :: OpenStack
12 Intended Audience :: Developers
13 Intended Audience :: Information Technology
14 License :: OSI Approved :: Apache Software License
15 Operating System :: OS Independent
16 Programming Language :: Python
17 Programming Language :: Python :: 2
18 Programming Language :: Python :: 2.6
19 Programming Language :: Python :: 2.7
20 Programming Language :: Python :: 3
21 Programming Language :: Python :: 3.3
22
23[files]
24packages =
25 cathead
26
27[global]
28setup-hooks =
29 pbr.hooks.setup_hook
30
31[wheel]
32universal = 1
33
34[entry_points]
35console_scripts =
36 cathead = cathead.cathead:main
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..7363757
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,30 @@
1#!/usr/bin/env python
2# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13# implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
18import setuptools
19
20# In python < 2.7.4, a lazy loading of package `pbr` will break
21# setuptools if some other modules registered functions in `atexit`.
22# solution from: http://bugs.python.org/issue15881#msg170215
23try:
24 import multiprocessing # noqa
25except ImportError:
26 pass
27
28setuptools.setup(
29 setup_requires=['pbr'],
30 pbr=True)
diff --git a/test-requirements.txt b/test-requirements.txt
new file mode 100644
index 0000000..5d34800
--- /dev/null
+++ b/test-requirements.txt
@@ -0,0 +1,6 @@
1hacking
2freezegun
3python-subunit>=0.0.18
4testrepository>=0.0.18
5testtools>=0.9.34
6mock>=1.0
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tests/__init__.py
diff --git a/tests/test_cathead.py b/tests/test_cathead.py
new file mode 100644
index 0000000..3d81d96
--- /dev/null
+++ b/tests/test_cathead.py
@@ -0,0 +1,9 @@
1import unittest
2
3from cathead import cathead
4
5
6class CatheadTestCase(unittest.TestCase):
7
8 def test_cathead(self):
9 cathead.Cathead(None)
diff --git a/tests/test_certwatcher.py b/tests/test_certwatcher.py
new file mode 100644
index 0000000..71abf2c
--- /dev/null
+++ b/tests/test_certwatcher.py
@@ -0,0 +1,50 @@
1import datetime
2import tempfile
3import unittest
4
5import freezegun
6import mock
7
8from cathead import certwatch
9import cathead.x509
10
11
12class CertWatcherTestCase(unittest.TestCase):
13
14 @mock.patch.object(cathead.x509, 'get_expire_date')
15 def test_expires_in_window(self, mock_get_expire_date):
16 key = tempfile.NamedTemporaryFile()
17 cert = tempfile.NamedTemporaryFile()
18 watcher = certwatch.CertWatcher(key.name, cert.name,
19 "common name", None,
20 refresh_window=40)
21 mock_get_expire_date.return_value = datetime.datetime(2014, 12, 19,
22 15, 18, 53)
23 with freezegun.freeze_time("2014-12-19 15:18:10"):
24 self.assertFalse(watcher._expires_in_window())
25
26 with freezegun.freeze_time("2014-12-19 15:18:14"):
27 self.assertTrue(watcher._expires_in_window())
28
29 @mock.patch.object(cathead.x509, 'get_expire_date')
30 @mock.patch.object(cathead.x509, 'generate_csr')
31 def test_check_and_update(self, mock_generate_csr, mock_get_expire_date):
32 mock_get_expire_date.return_value = datetime.datetime(2014, 12, 19,
33 15, 18, 53)
34 mock_generate_csr.return_value = "hello csr"
35
36 callback = mock.Mock()
37 key = tempfile.NamedTemporaryFile()
38 cert = tempfile.NamedTemporaryFile()
39 watcher = certwatch.CertWatcher(key.name, cert.name, 'common_name',
40 None, on_refresh_success=callback,
41 refresh_window=40)
42
43 watcher.ca_driver = mock.Mock()
44 watcher.ca_driver.sign.return_value = "hello cert"
45
46 watcher.check_and_update()
47
48 self.assertEqual("hello cert", cert.file.read())
49 watcher.ca_driver.called_once_with("hello csr")
50 callback.assert_called_once_with()
diff --git a/tests/test_ecadriver.py b/tests/test_ecadriver.py
new file mode 100644
index 0000000..5c1d747
--- /dev/null
+++ b/tests/test_ecadriver.py
@@ -0,0 +1,11 @@
1import unittest
2
3from cathead import cadriver
4from cathead.drivers import eca
5
6
7class EcaDriverTestCase(unittest.TestCase):
8
9 def test_sign(self):
10 driver = eca.EcaDriver("host", "port", "user", "password")
11 self.assertTrue(isinstance(driver, cadriver.CaDriver))
diff --git a/tests/test_selfsigndriver.py b/tests/test_selfsigndriver.py
new file mode 100644
index 0000000..d82d539
--- /dev/null
+++ b/tests/test_selfsigndriver.py
@@ -0,0 +1,23 @@
1import re
2import unittest
3import tempfile
4
5from cathead.drivers import selfsign
6from cathead import x509
7
8
9class SelfSignDriverTestCase(unittest.TestCase):
10
11 def test_sign(self):
12 key = x509.generate_key()
13 keyfile = tempfile.NamedTemporaryFile()
14 keyfile.write(key)
15 keyfile.flush()
16 driver = selfsign.SelfSignDriver(keyfile.name)
17 csr = x509.generate_csr(key, '192')
18 cert = driver.sign(csr)
19 match = re.search("^-----BEGIN CERTIFICATE-----"
20 ".*"
21 "-----END CERTIFICATE-----",
22 cert, re.MULTILINE | re.DOTALL)
23 self.assertTrue(match)
diff --git a/tests/test_x509.py b/tests/test_x509.py
new file mode 100644
index 0000000..b8b8879
--- /dev/null
+++ b/tests/test_x509.py
@@ -0,0 +1,48 @@
1import datetime
2import re
3import unittest
4
5import mock
6import oslo_concurrency.processutils
7
8from cathead import x509
9
10
11class X509TestCase(unittest.TestCase):
12
13 @mock.patch.object(oslo_concurrency.processutils, 'execute')
14 def test_get_expire_date(self, mock_execute):
15 mock_execute.return_value = (("notBefore=Dec 19 03:18:43 2014 GMT\n"
16 "notAfter=Dec 19 15:18:43 2014 GMT\n"
17 "issuer= /C=UK/O=hp/CN=CertAuthority\n"
18 "subject= /CN=192.0.2.26\n"),)
19 expected_date = datetime.datetime(2014, 12, 19, 15, 18, 43)
20
21 self.assertEqual(x509.get_expire_date('-'), expected_date)
22
23 def test_generate_csr(self):
24 key = x509.generate_key()
25 csr = x509.generate_csr(key, "secert cert auth")
26 match = re.search("^-----BEGIN CERTIFICATE REQUEST-----"
27 ".*"
28 "-----END CERTIFICATE REQUEST-----",
29 csr, re.MULTILINE | re.DOTALL)
30 self.assertTrue(match)
31
32 def test_generate_key(self):
33 key = x509.generate_key()
34 match = re.search("^-----BEGIN RSA PRIVATE KEY-----"
35 ".*"
36 "-----END RSA PRIVATE KEY-----",
37 key, re.MULTILINE | re.DOTALL)
38 self.assertTrue(match)
39
40 def test_generate_cert(self):
41 key = x509.generate_key()
42 csr = x509.generate_csr(key, "unknown")
43 cert = x509.generate_cert(key, csr)
44 match = re.search("^-----BEGIN CERTIFICATE-----"
45 ".*"
46 "-----END CERTIFICATE-----",
47 cert, re.MULTILINE | re.DOTALL)
48 self.assertTrue(match)
diff --git a/tests/util.py b/tests/util.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tests/util.py
diff --git a/tox.ini b/tox.ini
new file mode 100644
index 0000000..f02792f
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,28 @@
1[tox]
2distribute = False
3envlist = py33,py34,py26,py27,pep8
4
5[testenv]
6setenv = VIRTUAL_ENV={envdir}
7deps = -r{toxinidir}/requirements.txt
8 -r{toxinidir}/test-requirements.txt
9commands = python setup.py testr --slowest --testr-args='{posargs}'
10
11[testenv:pep8]
12commands = flake8
13
14[testenv:cover]
15setenv = VIRTUAL_ENV={envdir}
16commands =
17 python setup.py testr --coverage
18
19[testenv:venv]
20commands = {posargs}
21
22[testenv:docs]
23commands = python setup.py build_sphinx
24
25[flake8]
26show-source = True
27exclude = .tox,dist,doc,*.egg,build
28builtins = _