Merge lp:~jacekn/charm-helpers/charm-helpers-ssl into lp:charm-helpers

Proposed by Jacek Nykis
Status: Merged
Merged at revision: 76
Proposed branch: lp:~jacekn/charm-helpers/charm-helpers-ssl
Merge into: lp:charm-helpers
Diff against target: 151 lines (+139/-0)
2 files modified
charmhelpers/contrib/ssl/__init__.py (+79/-0)
tests/contrib/ssl/test_ssl.py (+60/-0)
To merge this branch: bzr merge lp:~jacekn/charm-helpers/charm-helpers-ssl
Reviewer Review Type Date Requested Status
Matthew Wedgwood (community) Approve
Review via email: mp+182365@code.launchpad.net

Description of the change

Added contrib.ssl module which can create selfsigned SSL certificates.

To post a comment you must log in.
Revision history for this message
Matthew Wedgwood (mew) wrote :

This looks quite helpful. Thanks.

I see a few issues here.

Running this as generate_selfsigned("mykey", "mycert") fails:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "charmhelpers/contrib/ssl/__init__.py", line 19, in generate_selfsigned
    subprocess.check_call(cmd)
UnboundLocalError: local variable 'cmd' referenced before assignment

There should be a test that catches this.

Furthermore, the "subject" argument is a little opaque. I somewhat expected to be able to pass it a hostname, but that's not at all what's needed. I'd recommend any combination of:

1. Adding a docstring with a little explanation
2. Exposing the subject components as function args (rather than as one dict)

As a bonus, it might be nice to allow users to specify the number of bits the for the cert as 1024 will inevitably fall out of vogue.
3. Building a simple "CertificateSubject" class to help users construct a valid subject
4. Providing reasonable defaults.

review: Needs Fixing
75. By Jacek Nykis

Added docstring to the generate_selfsigned function. Improved the function to accept single cn argument and partial subject dict

Revision history for this message
Matthew Wedgwood (mew) wrote :

I'm able to get the new function succeed using the "cn" parameter, but it explodes[1] when I try to use "subject." I've tried that one with various permutations on the keys included in the dict. I haven't tested the "config" parameter.

Also, I notice you're returning False for failures, but when the function actually succeeds, it returns None. You might want an explicit "return True" at the end.

[1] http://pastebin.ubuntu.com/6034287/

review: Needs Fixing
76. By Jacek Nykis

Added more error checking to contrib.ssl.generate_selfsigned function

Revision history for this message
Jacek Nykis (jacekn) wrote :

I added more error checking and return True statement.

Your test is failing as expected, country code should be 2 letter code. With my changes this will be picked up by the try/except block I added but there is no way I can return exact reason for openssl command failure.

Revision history for this message
Matthew Wedgwood (mew) wrote :

Ah, that makes sense. With these changes, LGTM.

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== added directory 'charmhelpers/contrib/ssl'
=== added file 'charmhelpers/contrib/ssl/__init__.py'
--- charmhelpers/contrib/ssl/__init__.py 1970-01-01 00:00:00 +0000
+++ charmhelpers/contrib/ssl/__init__.py 2013-08-28 09:12:15 +0000
@@ -0,0 +1,79 @@
1import subprocess
2from charmhelpers.core import hookenv
3
4
5def generate_selfsigned(keyfile, certfile, keysize="1024", config=None, subject=None, cn=None):
6 """Generate selfsigned SSL keypair
7
8 You must provide one of the 3 optional arguments:
9 config, subject or cn
10 If more than one is provided the leftmost will be used
11
12 Arguments:
13 keyfile -- (required) full path to the keyfile to be created
14 certfile -- (required) full path to the certfile to be created
15 keysize -- (optional) SSL key length
16 config -- (optional) openssl configuration file
17 subject -- (optional) dictionary with SSL subject variables
18 cn -- (optional) cerfificate common name
19
20 Required keys in subject dict:
21 cn -- Common name (eq. FQDN)
22
23 Optional keys in subject dict
24 country -- Country Name (2 letter code)
25 state -- State or Province Name (full name)
26 locality -- Locality Name (eg, city)
27 organization -- Organization Name (eg, company)
28 organizational_unit -- Organizational Unit Name (eg, section)
29 email -- Email Address
30 """
31
32 cmd = []
33 if config:
34 cmd = ["/usr/bin/openssl", "req", "-new", "-newkey",
35 "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509",
36 "-keyout", keyfile,
37 "-out", certfile, "-config", config]
38 elif subject:
39 ssl_subject = ""
40 if "country" in subject:
41 ssl_subject = ssl_subject + "/C={}".format(subject["country"])
42 if "state" in subject:
43 ssl_subject = ssl_subject + "/ST={}".format(subject["state"])
44 if "locality" in subject:
45 ssl_subject = ssl_subject + "/L={}".format(subject["locality"])
46 if "organization" in subject:
47 ssl_subject = ssl_subject + "/O={}".format(subject["organization"])
48 if "organizational_unit" in subject:
49 ssl_subject = ssl_subject + "/OU={}".format(subject["organizational_unit"])
50 if "cn" in subject:
51 ssl_subject = ssl_subject + "/CN={}".format(subject["cn"])
52 else:
53 hookenv.log("When using \"subject\" argument you must " \
54 "provide \"cn\" field at very least")
55 return False
56 if "email" in subject:
57 ssl_subject = ssl_subject + "/emailAddress={}".format(subject["email"])
58
59 cmd = ["/usr/bin/openssl", "req", "-new", "-newkey",
60 "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509",
61 "-keyout", keyfile,
62 "-out", certfile, "-subj", ssl_subject]
63 elif cn:
64 cmd = ["/usr/bin/openssl", "req", "-new", "-newkey",
65 "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509",
66 "-keyout", keyfile,
67 "-out", certfile, "-subj", "/CN={}".format(cn)]
68
69 if not cmd:
70 hookenv.log("No config, subject or cn provided," \
71 "unable to generate self signed SSL certificates")
72 return False
73 try:
74 subprocess.check_call(cmd)
75 return True
76 except Exception as e:
77 print "Execution of openssl command failed:\n{}".format(e)
78 return False
79
080
=== added directory 'tests/contrib/ssl'
=== added file 'tests/contrib/ssl/__init__.py'
=== added file 'tests/contrib/ssl/test_ssl.py'
--- tests/contrib/ssl/test_ssl.py 1970-01-01 00:00:00 +0000
+++ tests/contrib/ssl/test_ssl.py 2013-08-28 09:12:15 +0000
@@ -0,0 +1,60 @@
1import subprocess
2
3from mock import patch, call, MagicMock
4from testtools import TestCase
5
6from charmhelpers.contrib import ssl
7
8
9class HelpersTest(TestCase):
10 @patch('subprocess.check_call')
11 def test_generate_selfsigned_dict(self, mock_call):
12 subject = {"country": "UK",
13 "locality": "my_locality",
14 "state": "my_state",
15 "organization": "my_organization",
16 "organizational_unit": "my_unit",
17 "cn": "mysite.example.com",
18 "email": "me@example.com"
19 }
20
21 ssl.generate_selfsigned("mykey.key", "mycert.crt", subject=subject)
22 mock_call.assert_called_with(['/usr/bin/openssl', 'req', '-new',
23 '-newkey', 'rsa:1024', '-days', '365',
24 '-nodes', '-x509', '-keyout',
25 'mykey.key', '-out', 'mycert.crt',
26 '-subj',
27 '/C=UK/ST=my_state/L=my_locality'
28 '/O=my_organization/OU=my_unit'
29 '/CN=mysite.example.com'
30 '/emailAddress=me@example.com']
31 )
32
33 @patch('charmhelpers.core.hookenv.log')
34 def test_generate_selfsigned_failure(self, mock_log):
35 # This is NOT enough, functino requires cn key
36 subject = {"country": "UK",
37 "locality": "my_locality"}
38
39 result = ssl.generate_selfsigned("mykey.key", "mycert.crt", subject=subject)
40 self.assertFalse(result)
41
42
43 @patch('subprocess.check_call')
44 def test_generate_selfsigned_file(self, mock_call):
45 ssl.generate_selfsigned("mykey.key", "mycert.crt", config="test.cnf")
46 mock_call.assert_called_with(['/usr/bin/openssl', 'req', '-new',
47 '-newkey', 'rsa:1024', '-days', '365',
48 '-nodes', '-x509', '-keyout',
49 'mykey.key', '-out', 'mycert.crt',
50 '-config', 'test.cnf'])
51
52
53 @patch('subprocess.check_call')
54 def test_generate_selfsigned_cn_key(self, mock_call):
55 ssl.generate_selfsigned("mykey.key", "mycert.crt", keysize="2048", cn="mysite.example.com")
56 mock_call.assert_called_with(['/usr/bin/openssl', 'req', '-new',
57 '-newkey', 'rsa:2048', '-days', '365',
58 '-nodes', '-x509', '-keyout',
59 'mykey.key', '-out', 'mycert.crt',
60 '-subj', '/CN=mysite.example.com'])

Subscribers

People subscribed via source and target branches