summaryrefslogtreecommitdiff
path: root/certs/makecerts.py
blob: 9f7d211f666f99ce41b06e3dda18ff0efe2e25fc (plain)
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************

import os, sys, shutil, glob, socket, subprocess

def usage():
    print("Usage: " + sys.argv[0] + " [options] [ip-address]")
    print("")
    print("Options:")
    print("-h    Show this message.")
    print("-d    Debugging output.")
    sys.exit(1)

try:
    from subprocess import DEVNULL
except ImportError:
    DEVNULL = open(os.devnull, 'wb')

debug = False
ipAddress = None

#
# Check arguments
#
debug = False
ipAddress = None
for x in sys.argv[1:]:
    if x == "-h":
        usage()
        sys.exit(0)
    elif x == "-d":
        debug = True
    elif x.startswith("-"):
        print(sys.argv[0] + ": unknown option `" + x + "'")
        print("")
        usage()
        sys.exit(1)
    else:
        ipAddress = x

if not ipAddress:
    try:
        ipAddress = socket.gethostbyname(socket.gethostname())
    except:
        ipAddress = "127.0.0.1"

cwd = os.getcwd()
if not os.path.exists("ImportKey.class") or os.path.basename(cwd) != "certs":
    print("You must run this script from the certs directory")
    sys.exit(1)

#
# Make sure keytool is available
#
if subprocess.call("keytool", shell=True, stdout=DEVNULL, stderr=DEVNULL) != 0:
    print("error: couldn't run keytool, make sure the Java bin directory is in your PATH,\nkeytool is required to generate Java certificates")
    sys.exit(1)

bksSupport = True
if subprocess.call("javap org.bouncycastle.jce.provider.BouncyCastleProvider", shell=True, stdout=DEVNULL, stderr=DEVNULL) != 0:
    print("warning: couldn't find Bouncy Castle provider, Android certificates won't be created")
    bksSupport = False
    
while True:
    print("The IP address used for the server certificate will be: " + ipAddress)
    sys.stdout.write("Do you want to keep this IP address? (y/n) [y]")
    sys.stdout.flush()
    input = sys.stdin.readline().strip()
    if input == 'n':
        sys.stdout.write("IP : ")
        sys.stdout.flush()
        ipAddress = sys.stdin.readline().strip()
    else:
        break

certs = "."
caHome = os.path.abspath(os.path.join(certs, "ca")).replace('\\', '/')

#
# Static configuration file data.
#
configFiles = {\
"ca.cnf":"\
# **********************************************************************\n\
#\n\
# Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.\n\
#\n\
# This copy of Ice is licensed to you under the terms described in the\n\
# ICE_LICENSE file included in this distribution.\n\
#\n\
# **********************************************************************\n\
\n\
# Configuration file for the CA. This file is generated by iceca init.\n\
# DO NOT EDIT!\n\
\n\
###############################################################################\n\
###  Self Signed Root Certificate\n\
###############################################################################\n\
\n\
[ ca ]\n\
default_ca = ice\n\
\n\
[ ice ]\n\
default_days     = 1825    # How long certs are valid.\n\
default_md       = sha256  # The Message Digest type.\n\
preserve         = no      # Keep passed DN ordering?\n\
\n\
[ req ]\n\
default_bits        = 2048\n\
default_keyfile     = {0}/cakey.pem\n\
default_md          = sha256\n\
prompt              = no\n\
distinguished_name  = dn\n\
x509_extensions     = extensions\n\
\n\
[ extensions ]\n\
basicConstraints = CA:true\n\
\n\
# PKIX recommendation.\n\
subjectKeyIdentifier = hash\n\
authorityKeyIdentifier = keyid:always,issuer:always\n\
\n\
[dn]\n\
countryName            = US\n\
stateOrProvinceName    = Florida\n\
localityName           = Jupiter\n\
organizationName       = ZeroC, Inc.\n\
organizationalUnitName = Ice\n\
commonName             = ZeroC Tests and Demos CA\n\
emailAddress           = info@zeroc.com\n\
",\
"ice.cnf":"\
# **********************************************************************\n\
#\n\
# Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.\n\
#\n\
# This copy of Ice is licensed to you under the terms described in the\n\
# ICE_LICENSE file included in this distribution.\n\
#\n\
# **********************************************************************\n\
\n\
# Configuration file to sign a certificate. This file is generated by iceca init.\n\
# DO NOT EDIT!!\n\
\n\
[ ca ]\n\
default_ca = ice\n\
\n\
[ ice ]\n\
dir              = {0}              # Where everything is kept.\n\
private_key      = $dir/cakey.pem   # The CA Private Key.\n\
certificate      = $dir/cacert.pem  # The CA Certificate.\n\
database         = $dir/index.txt           # Database index file.\n\
new_certs_dir    = $dir                     # Default loc for new certs.\n\
serial           = $dir/serial              # The current serial number.\n\
certs            = $dir                     # Where issued certs are kept.\n\
RANDFILE         = $dir/.rand               # Private random number file.\n\
default_days     = 1825                     # How long certs are valid.\n\
default_md       = sha256                      # The Message Digest type.\n\
preserve         = yes                      # Keep passed DN ordering?\n\
\n\
policy           = ca_policy\n\
x509_extensions  = certificate_extensions\n\
\n\
[ certificate_extensions ]\n\
basicConstraints = CA:false\n\
\n\
# PKIX recommendation.\n\
subjectKeyIdentifier = hash\n\
authorityKeyIdentifier = keyid:always,issuer:always\n\
subjectAltName         = DNS:{1}, IP:{2}\n\
\n\
[ ca_policy ]\n\
countryName            = match\n\
stateOrProvinceName    = match\n\
organizationName       = match\n\
organizationalUnitName = optional\n\
emailAddress           = optional\n\
commonName             = supplied\n\
\n\
[ req ]\n\
default_bits        = 1024\n\
default_md          = sha256\n\
prompt              = no\n\
distinguished_name  = dn\n\
x509_extensions     = extensions\n\
\n\
[ extensions ]\n\
basicConstraints = CA:false\n\
\n\
# PKIX recommendation.\n\
subjectKeyIdentifier = hash\n\
authorityKeyIdentifier = keyid:always,issuer:always\n\
keyUsage = nonRepudiation, digitalSignature, keyEncipherment\n\
\n\
[dn]\n\
countryName            = US\n\
stateOrProvinceName    = Florida\n\
localityName           = Jupiter\n\
organizationName       = ZeroC, Inc.\n\
organizationalUnitName = Ice\n\
commonName             = {3}\n\
emailAddress           = info@zeroc.com\n\
" }

def generateConf(file, dns = None, ip = None, commonName = None):
    cnf = open(os.path.join(caHome, file), "w")
    if dns and ip and commonName:
        cnf.write(configFiles[file].format(caHome, dns, ip, commonName))
    else:
        cnf.write(configFiles[file].format(caHome))
    cnf.close()

def run(cmd):
    if debug:
        print("[debug]", cmd)

    p = subprocess.Popen(cmd,
                         shell = True,
                         stdin = subprocess.PIPE,
                         stdout = subprocess.STDOUT if debug else subprocess.PIPE,
                         stderr = subprocess.STDERR if debug else subprocess.PIPE,
                         bufsize = 0)
    if p.wait() != 0:
        print("command failed:" + cmd + "\n")
        for line in p.stdout.readlines():
            print(line.decode("utf-8").strip())
        sys.exit(1)
    
def runOpenSSL(command):
    run("openssl " + command)

def jksToBks(source, target):
    cmd = "keytool -importkeystore -srckeystore " + source + " -destkeystore " + target + \
          " -srcstoretype JKS -deststoretype BKS -srcstorepass password -deststorepass password " + \
          "-provider org.bouncycastle.jce.provider.BouncyCastleProvider -noprompt"
    if debug:
        print("[debug]", cmd)

    p = subprocess.Popen(cmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE,
                        stderr = subprocess.STDOUT, bufsize = 0)

    while(True):
        line = p.stdout.readline()            
        if p.poll() is not None and not line:
            # The process terminated
            break
            
        if line.find("java.lang.ClassNotFoundException: org.bouncycastle.jce.provider.BouncyCastleProvider") != -1:
            print("")
            print("WARNING: BouncyCastleProvider not found cannot export certificates for android")
            print("         demos in BKS format. You can download BKS provider from:")
            print("")
            print("            http://www.bouncycastle.org/")
            print("")
            print("         After download copy the JAR to $JAVA_HOME/lib/ext where JAVA_HOME")
            print("         points to your JRE and run this script again.")
            print("")
            return False
        elif line.find("java.security.InvalidKeyException: Illegal key size") != -1:
            print("")
            print("WARNING: You need to install Java Cryptography Extension (JCE) Unlimited")
            print("         Strength. You can download it from Additional Resources section")
            print("         in Orcale Java Download page at:")
            print("")
            print("             http://www.oracle.com/technetwork/java/javase/downloads/index.html")
            print("")
            return False
        return True
    if p.poll() != 0:
        sys.exit(1)

def generateCert(desc, name, commonName = None):

    if not commonName:
        commonName = desc
    
    generateConf("ice.cnf", ipAddress, ipAddress, commonName)

    cert = os.path.join(certs, name + "_rsa1024_pub.pem")
    key = os.path.join(certs, name + "_rsa1024_priv.pem")
    sys.stdout.write("Generating new " + desc + " certificates... ")
    sys.stdout.flush()

    if os.path.exists(cert):
        os.remove(cert)
    if os.path.exists(key):
        os.remove(key)

    serial = os.path.join(caHome, "serial")
    f = open(serial, "r")
    serialNum = f.read().strip()
    f.close()
    
    tmpKey = os.path.join(caHome, serialNum + "_key.pem")
    tmpCert = os.path.join(caHome, serialNum + "_cert.pem")
    req = os.path.join(caHome, "req.pem")
    config = os.path.join(caHome, "ice.cnf")

    #
    # Generate PEM certificates
    #
    runOpenSSL("req -config " + config + " -newkey rsa:1024 -nodes -keyout " + tmpKey + " -keyform PEM -out " + req)
    runOpenSSL("ca -config " + config + " -batch -in " + req)

    shutil.move(os.path.join(caHome, serialNum + ".pem"), tmpCert)
    shutil.copyfile(tmpKey, key)
    shutil.copyfile(tmpCert, cert)
    os.remove(req)

    #
    # Generate PKCS12 certificates
    #
    runOpenSSL("pkcs12 -in " + cert + " -inkey " + key + " -export -out " + name + "_rsa1024.pfx" + \
               " -certpbe PBE-SHA1-RC4-40 -keypbe PBE-SHA1-RC4-40" + \
               " -passout pass:password -name " + desc)

    #
    # Generate Java keystore
    #
    tmpFile = desc + ".p12"
    runOpenSSL("pkcs12 -in " + cert + " -inkey " + key + " -export -out " + tmpFile + \
               " -name rsakey -passout pass:password -certfile cacert.pem")
    run("java -classpath . ImportKey " + tmpFile + " rsakey cacert.pem " + desc + ".jks password")
    os.remove(tmpFile)

    #
    # Generate BKS for Android if supported
    #
    if bksSupport:
        jksToBks(desc + ".jks", desc + ".bks")
    
    if not debug:
        print("ok")


#
# Generate the CA certificate and database
#
if os.path.exists(caHome):
    shutil.rmtree(caHome)

sys.stdout.write("Generating new CA certificate and key... ")
sys.stdout.flush()
os.mkdir(caHome)

f = open(os.path.join(caHome, "serial"), "w")
f.write("01")
f.close()

f = open(os.path.join(caHome, "index.txt"), "w")
f.truncate(0)
f.close()

generateConf("ca.cnf")

config = os.path.join(caHome, "ca.cnf")
caCert = os.path.join(caHome, "cacert.pem")
runOpenSSL("req -config " + config + " -x509 -days 1825 -newkey rsa:1024 -out " + caCert + " -outform PEM -nodes")
runOpenSSL("x509 -in " + caCert + " -outform DER -out " + os.path.join(certs, "cacert.der")) # Convert to DER
shutil.copyfile(caCert, os.path.join(certs, "cacert.pem"))
shutil.copyfile(os.path.join(caHome, "cakey.pem"), os.path.join(certs, "cakey.pem"))
if os.path.exists("certs.jks"):
    os.remove("certs.jks")
run("keytool -import -alias cacert -file cacert.der -keystore certs.jks -storepass password -noprompt")
if not debug:
    print("ok")

#
# Generate the client and the server certificates
#
generateCert("server", "s", ipAddress) # commonName = ipAddress
generateCert("client", "c")

os.chdir("..")