/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2929.3.11 by Vincent Ladeuil
Ssl files needed for the test https server.
1
#! /usr/bin/env python
2
3
# Copyright (C) 2007 Canonical Ltd
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
from cStringIO import StringIO
42
import optparse
43
import os
44
from subprocess import (
45
    CalledProcessError,
46
    Popen,
47
    PIPE,
48
    )
49
50
from bzrlib import (
51
    osutils,
52
    )
53
from bzrlib.tests import (
54
    ssl_certs,
55
    )
56
57
def error(s):
58
    print s
59
    exit(1)
60
61
def needs(request, *paths):
62
    """Errors out if the specified path does not exists"""
63
    missing = [p for p in paths if not os.path.exists(p)]
64
    if missing:
65
        error('%s needs: %s' % (request, ','.join(missing)))
66
67
68
def rm_f(path):
69
    """rm -f path"""
70
    try:
71
        os.unlink(path)
72
    except:
73
        pass
74
75
def _openssl(args, input=None):
76
    """Execute a command in a subproces feeding stdin with the provided input.
77
78
    :return: (returncode, stdout, stderr)
79
    """
80
    cmd = ['openssl'] + args
81
    proc = Popen(cmd, stdin=PIPE)
82
    (stdout, stderr) = proc.communicate(input)
83
    if proc.returncode:
84
        # Basic error handling, all commands should succeed
85
        raise CalledProcessError(proc.returncode, cmd)
86
    return proc.returncode, stdout, stderr
87
88
89
ssl_params=dict(
90
    # Passwords
91
    server_pass='I will protect the communications',
92
    server_challenge_pass='Challenge for the CA',
93
    ca_pass='I am the authority for the whole... localhost',
94
    # CA identity
95
    ca_country_code='BZ',
96
    ca_state='Internet',
97
    ca_locality='Bazaar',
98
    ca_organization='Distributed',
99
    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).
100
    ca_name='Master of certificates',
2929.3.11 by Vincent Ladeuil
Ssl files needed for the test https server.
101
    ca_email='cert@no.spam',
102
    # Server identity
103
    server_country_code='LH',
104
    server_state='Internet',
105
    server_locality='LocalHost',
106
    server_organization='Testing Ltd',
107
    server_section='https server',
2929.3.18 by Vincent Ladeuil
Fix the server name in script and ssl files.
108
    server_name='localhost', # Always accessed under that name
2929.3.11 by Vincent Ladeuil
Ssl files needed for the test https server.
109
    server_email='https_server@locahost',
110
    server_optional_company_name='',
111
    )
112
113
114
def build_ca_key():
115
    """Generate an ssl certificate authority private key."""
116
    key_path = ssl_certs.build_path('ca.key')
117
    rm_f(key_path)
118
    _openssl(['genrsa', '-passout', 'stdin', '-des3', '-out', 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).
119
             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.
120
121
122
def build_ca_certificate():
123
    """Generate an ssl certificate authority private key."""
124
    key_path = ssl_certs.build_path('ca.key')
125
    needs('Building ca.crt', key_path)
126
    cert_path = ssl_certs.build_path('ca.crt')
127
    rm_f(cert_path)
128
    _openssl(['req', '-passin', 'stdin', '-new', '-x509',
129
              # Will need to be generated again in 10 years -- vila 20071122
130
              '-days', '3650',
131
              '-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).
132
             input='%(ca_pass)s\n'
2929.3.11 by Vincent Ladeuil
Ssl files needed for the test https server.
133
             '%(ca_country_code)s\n'
134
             '%(ca_state)s\n'
135
             '%(ca_locality)s\n'
136
             '%(ca_organization)s\n'
137
             '%(ca_section)s\n'
138
             '%(ca_name)s\n'
139
             '%(ca_email)s\n'
140
             % ssl_params)
141
142
143
def build_server_key():
144
    """Generate an ssl server private key.
145
146
    We generates a key with a password and then copy it without password so
147
    that as server can user it without prompting.
148
    """
149
    key_path = ssl_certs.build_path('server_with_pass.key')
150
    rm_f(key_path)
151
    _openssl(['genrsa', '-passout', 'stdin', '-des3', '-out', 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).
152
             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.
153
154
    key_nopass_path = ssl_certs.build_path('server_without_pass.key')
155
    rm_f(key_nopass_path)
156
    _openssl(['rsa', '-passin', 'stdin', '-in', key_path,
157
              '-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).
158
             input='%(server_pass)s\n' % ssl_params)
2929.3.11 by Vincent Ladeuil
Ssl files needed for the test https server.
159
160
161
def build_server_signing_request():
162
    """Create a CSR (certificate signing request) to get signed by the CA"""
163
    key_path = ssl_certs.build_path('server_with_pass.key')
164
    needs('Building server.csr', key_path)
165
    server_csr_path = ssl_certs.build_path('server.csr')
166
    rm_f(server_csr_path)
167
    _openssl(['req', '-passin', 'stdin', '-new', '-key', key_path,
168
              '-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).
169
             input='%(server_pass)s\n'
2929.3.11 by Vincent Ladeuil
Ssl files needed for the test https server.
170
             '%(server_country_code)s\n'
171
             '%(server_state)s\n'
172
             '%(server_locality)s\n'
173
             '%(server_organization)s\n'
174
             '%(server_section)s\n'
175
             '%(server_name)s\n'
176
             '%(server_email)s\n'
177
             '%(server_challenge_pass)s\n'
178
             '%(server_optional_company_name)s\n'
179
             % ssl_params)
180
181
182
def sign_server_certificate():
183
    """CA signs server csr"""
184
    server_csr_path = ssl_certs.build_path('server.csr')
185
    ca_cert_path = ssl_certs.build_path('ca.crt')
186
    ca_key_path = ssl_certs.build_path('ca.key')
187
    needs('Signing server.crt', server_csr_path, ca_cert_path, ca_key_path)
188
    server_cert_path = ssl_certs.build_path('server.crt')
189
    rm_f(server_cert_path)
190
    _openssl(['x509', '-req', '-passin', 'stdin',
191
              # Will need to be generated again in 10 years -- vila 20071122
192
              '-days', '3650',
193
              '-in', server_csr_path,
194
              '-CA', ca_cert_path, '-CAkey', ca_key_path,
195
              '-set_serial', '01',
196
              '-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).
197
             input='%(ca_pass)s\n' % ssl_params)
2929.3.11 by Vincent Ladeuil
Ssl files needed for the test https server.
198
199
200
def build_ssls(name, options, builders):
201
    if options is not None:
202
        for item in options:
203
            builder = builders.get(item, None)
204
            if builder is None:
205
                error('%s is not a known %s' % (item, name))
206
            builder()
207
208
209
opt_parser = optparse.OptionParser(usage="usage: %prog [options]")
210
opt_parser.set_defaults(ca=False)
211
opt_parser.set_defaults(server=False)
212
opt_parser.add_option(
213
    "--ca", dest="ca", action="store_true",
214
    help="Generate CA key and certificate")
215
opt_parser.add_option(
216
    "--server", dest="server", action="store_true",
217
    help="Generate server key, certificate signing request and certificate")
218
opt_parser.add_option(
219
    "-k", "--key", dest="keys", action="append", metavar="KEY",
220
    help="generate a new KEY (several -k options can be specified)")
221
opt_parser.add_option(
222
    "-c", "--certificate", dest="certificates", action="append",
223
    metavar="CERTIFICATE",
224
    help="generate a new CERTIFICATE (several -c options can be specified)")
225
opt_parser.add_option(
226
    "-r", "--sign-request", dest="signing_requests", action="append",
227
    metavar="REQUEST",
228
    help="generate a new signing REQUEST (several -r options can be specified)")
229
opt_parser.add_option(
230
    "-s", "--sign", dest="signings", action="append",
231
    metavar="SIGNING",
232
    help="generate a new SIGNING (several -s options can be specified)")
233
234
235
key_builders = dict(ca=build_ca_key, server=build_server_key,)
236
certificate_builders = dict(ca=build_ca_certificate,)
237
signing_request_builders = dict(server=build_server_signing_request,)
238
signing_builders = dict(server=sign_server_certificate,)
239
240
241
if __name__ == '__main__':
242
    (Options, args) = opt_parser.parse_args()
243
    if (Options.ca or Options.server):
244
        if (Options.keys or Options.certificates or Options.signing_requests
245
            or Options.signings):
246
            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).
247
        # Handles --ca before --server so that both can be used in the same run
248
        # 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.
249
        if Options.ca:
250
            build_ca_key()
251
            build_ca_certificate()
252
        if Options.server:
253
            build_server_key()
254
            build_server_signing_request()
255
            sign_server_certificate()
256
    else:
257
        build_ssls('key', Options.keys, key_builders)
258
        build_ssls('certificate', Options.certificates, certificate_builders)
259
        build_ssls('signing request', Options.signing_requests,
260
                   signing_request_builders)
261
        build_ssls('signing', Options.signings, signing_builders)