/brz/remove-bazaar

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