1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
|
#! /usr/bin/env python
# Copyright (C) 2007 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""create_ssls.py -- create sll keys and certificates for tests.
The https server requires at least a key and a certificate to start.
SSL keys and certificates are created with openssl which may not be available
everywhere we want to run the test suite.
To simplify test writing, the necessary keys and certificates are generated by
this script and used by the tests.
Since creating these test keys and certificates requires a good knowledge of
openssl and a lot of typing, we record all the needed parameters here.
Since this will be used rarely, no effort has been made to handle exotic
errors, the basic policy is that openssl should be available in the path and
the parameters should be correct, any error will abort the script. Feel free to
enhance that.
This script provides options for building any individual files or two options
to build the certificate authority files (--ca) or the server files (--server).
"""
from cStringIO import StringIO
import optparse
import os
from subprocess import (
CalledProcessError,
Popen,
PIPE,
)
from bzrlib import (
osutils,
)
from bzrlib.tests import (
ssl_certs,
)
def error(s):
print s
exit(1)
def needs(request, *paths):
"""Errors out if the specified path does not exists"""
missing = [p for p in paths if not os.path.exists(p)]
if missing:
error('%s needs: %s' % (request, ','.join(missing)))
def rm_f(path):
"""rm -f path"""
try:
os.unlink(path)
except:
pass
def _openssl(args, input=None):
"""Execute a command in a subproces feeding stdin with the provided input.
:return: (returncode, stdout, stderr)
"""
cmd = ['openssl'] + args
proc = Popen(cmd, stdin=PIPE)
(stdout, stderr) = proc.communicate(input)
if proc.returncode:
# Basic error handling, all commands should succeed
raise CalledProcessError(proc.returncode, cmd)
return proc.returncode, stdout, stderr
ssl_params=dict(
# Passwords
server_pass='I will protect the communications',
server_challenge_pass='Challenge for the CA',
ca_pass='I am the authority for the whole... localhost',
# CA identity
ca_country_code='BZ',
ca_state='Internet',
ca_locality='Bazaar',
ca_organization='Distributed',
ca_section='VCS',
ca_name='Master of certificates',
ca_email='cert@no.spam',
# Server identity
server_country_code='LH',
server_state='Internet',
server_locality='LocalHost',
server_organization='Testing Ltd',
server_section='https server',
server_name='localhost', # Always accessed under that name
server_email='https_server@locahost',
server_optional_company_name='',
)
def build_ca_key():
"""Generate an ssl certificate authority private key."""
key_path = ssl_certs.build_path('ca.key')
rm_f(key_path)
_openssl(['genrsa', '-passout', 'stdin', '-des3', '-out', key_path, '4096'],
input='%(ca_pass)s\n%(ca_pass)s\n' % ssl_params)
def build_ca_certificate():
"""Generate an ssl certificate authority private key."""
key_path = ssl_certs.build_path('ca.key')
needs('Building ca.crt', key_path)
cert_path = ssl_certs.build_path('ca.crt')
rm_f(cert_path)
_openssl(['req', '-passin', 'stdin', '-new', '-x509',
# Will need to be generated again in 10 years -- vila 20071122
'-days', '3650',
'-key', key_path, '-out', cert_path],
input='%(ca_pass)s\n'
'%(ca_country_code)s\n'
'%(ca_state)s\n'
'%(ca_locality)s\n'
'%(ca_organization)s\n'
'%(ca_section)s\n'
'%(ca_name)s\n'
'%(ca_email)s\n'
% ssl_params)
def build_server_key():
"""Generate an ssl server private key.
We generates a key with a password and then copy it without password so
that as server can user it without prompting.
"""
key_path = ssl_certs.build_path('server_with_pass.key')
rm_f(key_path)
_openssl(['genrsa', '-passout', 'stdin', '-des3', '-out', key_path, '4096'],
input='%(server_pass)s\n%(server_pass)s\n' % ssl_params)
key_nopass_path = ssl_certs.build_path('server_without_pass.key')
rm_f(key_nopass_path)
_openssl(['rsa', '-passin', 'stdin', '-in', key_path,
'-out', key_nopass_path,],
input='%(server_pass)s\n' % ssl_params)
def build_server_signing_request():
"""Create a CSR (certificate signing request) to get signed by the CA"""
key_path = ssl_certs.build_path('server_with_pass.key')
needs('Building server.csr', key_path)
server_csr_path = ssl_certs.build_path('server.csr')
rm_f(server_csr_path)
_openssl(['req', '-passin', 'stdin', '-new', '-key', key_path,
'-out', server_csr_path],
input='%(server_pass)s\n'
'%(server_country_code)s\n'
'%(server_state)s\n'
'%(server_locality)s\n'
'%(server_organization)s\n'
'%(server_section)s\n'
'%(server_name)s\n'
'%(server_email)s\n'
'%(server_challenge_pass)s\n'
'%(server_optional_company_name)s\n'
% ssl_params)
def sign_server_certificate():
"""CA signs server csr"""
server_csr_path = ssl_certs.build_path('server.csr')
ca_cert_path = ssl_certs.build_path('ca.crt')
ca_key_path = ssl_certs.build_path('ca.key')
needs('Signing server.crt', server_csr_path, ca_cert_path, ca_key_path)
server_cert_path = ssl_certs.build_path('server.crt')
rm_f(server_cert_path)
_openssl(['x509', '-req', '-passin', 'stdin',
# Will need to be generated again in 10 years -- vila 20071122
'-days', '3650',
'-in', server_csr_path,
'-CA', ca_cert_path, '-CAkey', ca_key_path,
'-set_serial', '01',
'-out', server_cert_path,],
input='%(ca_pass)s\n' % ssl_params)
def build_ssls(name, options, builders):
if options is not None:
for item in options:
builder = builders.get(item, None)
if builder is None:
error('%s is not a known %s' % (item, name))
builder()
opt_parser = optparse.OptionParser(usage="usage: %prog [options]")
opt_parser.set_defaults(ca=False)
opt_parser.set_defaults(server=False)
opt_parser.add_option(
"--ca", dest="ca", action="store_true",
help="Generate CA key and certificate")
opt_parser.add_option(
"--server", dest="server", action="store_true",
help="Generate server key, certificate signing request and certificate")
opt_parser.add_option(
"-k", "--key", dest="keys", action="append", metavar="KEY",
help="generate a new KEY (several -k options can be specified)")
opt_parser.add_option(
"-c", "--certificate", dest="certificates", action="append",
metavar="CERTIFICATE",
help="generate a new CERTIFICATE (several -c options can be specified)")
opt_parser.add_option(
"-r", "--sign-request", dest="signing_requests", action="append",
metavar="REQUEST",
help="generate a new signing REQUEST (several -r options can be specified)")
opt_parser.add_option(
"-s", "--sign", dest="signings", action="append",
metavar="SIGNING",
help="generate a new SIGNING (several -s options can be specified)")
key_builders = dict(ca=build_ca_key, server=build_server_key,)
certificate_builders = dict(ca=build_ca_certificate,)
signing_request_builders = dict(server=build_server_signing_request,)
signing_builders = dict(server=sign_server_certificate,)
if __name__ == '__main__':
(Options, args) = opt_parser.parse_args()
if (Options.ca or Options.server):
if (Options.keys or Options.certificates or Options.signing_requests
or Options.signings):
error("--ca and --server can't be used with other options")
# Handles --ca before --server so that both can be used in the same run
# to generate all the files needed by the https test server
if Options.ca:
build_ca_key()
build_ca_certificate()
if Options.server:
build_server_key()
build_server_signing_request()
sign_server_certificate()
else:
build_ssls('key', Options.keys, key_builders)
build_ssls('certificate', Options.certificates, certificate_builders)
build_ssls('signing request', Options.signing_requests,
signing_request_builders)
build_ssls('signing', Options.signings, signing_builders)
|