-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathself-signed-ssl
executable file
·557 lines (484 loc) · 14 KB
/
self-signed-ssl
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#!/bin/bash
#
# This script simplifies the creation of certificate authorities,
# signing requests and self-signed TLS certificates using OpenSSL.
# Execute with help flag (-h|--help) for documentation.
set -e
VERSION="0.3.0"
#######################################
# General defaults
#######################################
SCRIPT_NAME="$(basename "$0")"
OUT="$(pwd)/"
CREATE_PATH=""
INTERACT="1"
BITS=2048
EXIT_CODE=0
#######################################
# Certificate authority defaults
#######################################
CA_KEY=""
CA=""
CA_ONLY=""
CA_EXT=""
TRUST=""
SUBJ=""
#######################################
# Certificate signing request
#######################################
CSR=""
CSR_ONLY=""
#######################################
# Certificate / subject defaults
#######################################
EXTFILE=""
DAYS=365 # 1 year
C=""
ST=""
L=""
O=""
OU=""
CN=""
HAS_CN=""
SAN=""
EMAIL=""
#######################################
# Safely exit the script
# Arguments:
# Exit code (number)
#######################################
_safe_exit() {
trap - INT TERM EXIT
exit "$@"
}
#######################################
# Check if packages are installed
# Arguments:
# List of commands (strings) to verify
# Outputs:
# Writes message to stderr and returns error code if package not present
#######################################
_require() {
while [ -n "$1" ]; do
if [ -z "$(command -v "$1")" ]; then
printf "Command '%s' not found\n" "${1}"
printf "Please ensure the program is installed and referenced in PATH variable\n" >&2
return 1
fi
shift
done
}
#######################################
# Validate script requirements
# Arguments:
# None
# Outputs:
# Exits script if required package not found
#######################################
_check_requirements() {
# Require OpenSSL
_require "openssl" || _safe_exit 1
# Require sudo if trusting CA
[ -z "${TRUST}" ] || _require "sudo" || _safe_exit 1
}
#######################################
# Display the help Screen
# Arguments:
# None
# Outputs:
# Writes help to stdout
#######################################
_help() {
cat <<EOF
${SCRIPT_NAME}
This script simplifies the creation of certificate authorities and self-signed TLS certificates using OpenSSL.
Usage:
${SCRIPT_NAME} [OPTIONS]
# Run with no arguments to be prompted for required values
${SCRIPT_NAME}
# Only create a certificate authority and trust the generated certificate
${SCRIPT_NAME} --ca-only --trust
# Only create a certificate signing request
${SCRIPT_NAME} --csr-only
# Generate a signed certificate using existing files
${SCRIPT_NAME} --ca='/path/to/CA.pem' --ca-key='/path/to/CA.key' --csr='/path/to/EXAMPLE.csr'
# Automate certificate generation
${SCRIPT_NAME} --no-interaction -c 'US' -s 'California' -l 'Los Angeles' -o 'Example Org' -u 'Example Unit' -n 'example.com' -a 'www.example.com'
General Options:
-h|--help Display this help and exit
-v|--version Display the script version and exit
-p|--path Path to output generated files
-d|--duration Validity duration of the certificate (in days)
-b|--bits Key size in bits (default '2048')
--no-interaction Disables interactive prompts for answers
Certificate Authority Options:
--ca Path to certificate authority cert file
(Generates new CA if not set)
--ca-key Path to certificate authority key file
(Generates new CA if not set)
--ca-only Instructs script to solely generate a certificate authority
--ca-ext Allow passing extensions to the CA request
-t|--trust Flag to trust certificate authority
(Do not set for default 'false')
Certificate Signing Request Options:
--csr Path to certificate signing request
(Generates new certificate signing request if not set)
--csr-only Instructs script to solely generate a certificate signing request
Certificate Options:
--extfile Path to file containing OpenSSL certificate extensions
(Optional - generated if not provided)
-c|--country Country Name (2 letter code)
-s|--state State or Province Name (full name)
-l|--locality Locality Name (eg, city)
-o|--organization Organization Name (eg, company)
-u|--unit Organizational Unit Name (eg, section)
-n|--common-name Common Name (e.g. server FQDN or YOUR name)
-a|--san Comma-delimited list of subject alternative names
-e|--email Email Address
EOF
}
#######################################
# Parse input arguments
# Arguments:
# All script arguments
# Output:
# Exits and outputs error to stderr when invalid argument provided
#######################################
_parse_args() {
while [ -n "$1" ]; do
if [[ " -h -v -t " =~ " $1 " ]]; then
# Parse arguments without values
ARG="${1}"
VALUE=""
shift
elif [ "${1:0:2}" == "--" ] || [ "${1:2:1}" == "=" ]; then
# Parse arguments with "="
ARG=${1%%=*}
VALUE=${1/$ARG=/}
shift
else
# Parse arguments separated by space
ARG="$1"
VALUE="$2"
shift 2
fi
case $ARG in
# General
-h|--help) _help; _safe_exit 0;;
-v|--version) printf "${SCRIPT_NAME} version: ${VERSION}\n"; _safe_exit 0;;
-p|--path) OUT="${VALUE}";;
--path-create) CREATE_PATH="1";;
-d|--duration) DAYS="${VALUE}";;
-b|--bits) BITS="${VALUE}";;
--no-interaction) INTERACT="";;
# CA
--ca|--ca-cert) CA="${VALUE}";;
--ca-key) CA_KEY="${VALUE}";;
--ca-only) CA_ONLY=1;;
--ca-ext) CA_EXT="${VALUE}";;
-t|--trust) TRUST=1;;
# CSR
--csr) CSR="${VALUE}";;
--csr-only) CSR_ONLY=1;;
# Cert
--extfile) EXTFILE="${VALUE}";;
-c|--country) C="${VALUE}";;
-s|--state) ST="${VALUE}";;
-l|--locality) L="${VALUE}";;
-o|--organization) O="${VALUE}";;
-u|--unit) OU="${VALUE}";;
-n|--common-name) CN="${VALUE}"; HAS_CN=1;;
-a|--san) SAN="${VALUE}";;
-e|--email) EMAIL="${VALUE}";;
# Invalid arguments
*)
printf "Error: unknown parameter '%s'\n" "${ARG}" >&2
_help
_safe_exit 1
;;
esac
done
}
#######################################
# Build subject alternative names variable
# Arguments:
# None
#######################################
_build_san() {
# Subject Alternative Names
if [ -z "${SAN}" ] && [ -z "${HAS_CN}" ] && [ -n "${INTERACT}" ]; then
printf "Subject Alternative Name(s) (e.g. subdomains) []: "
read -r SAN
fi
# Build DNS
i=0
read -r -a URLS <<< "${CN} ${SAN//,/ }"
SAN=""
for u in "${URLS[@]}"; do
if [ -n "${u}" ]; then
i=$((i+1))
SAN="${SAN}DNS.${i} = ${u// /}"$'\n'
fi
done
}
#######################################
# Build certificate subject
# Arguments:
# None
#######################################
_build_subj() {
if [ -n "${C}" ]; then
SUBJ="${SUBJ}/C=${C}"
fi
if [ -n "${ST}" ]; then
SUBJ="${SUBJ}/ST=${ST}"
fi
if [ -n "${L}" ]; then
SUBJ="${SUBJ}/L=${L}"
fi
if [ -n "${O}" ]; then
SUBJ="${SUBJ}/O=${O}"
fi
if [ -n "${OU}" ]; then
SUBJ="${SUBJ}/OU=${OU}"
fi
if [ -n "${CN}" ]; then
SUBJ="${SUBJ}/CN=${CN}"
fi
if [ -n "${EMAIL}" ]; then
SUBJ="${SUBJ}/emailAddress=${EMAIL}"
fi
}
#######################################
# Check that required arguments were provided and update globals
# Arguments:
# None
#######################################
_validate_args() {
# Certificate authority files
if [ -n "${CA_KEY}" ] && [ -n "${CA}" ]; then
if [ ! -f "${CA_KEY}" ]; then
printf "The specified certificate authorify key file does not exist\n" >&2
_safe_exit 1
fi
if [ ! -f "${CA}" ]; then
printf "The specified certificate authorify file does not exist\n" >&2
_safe_exit 1
fi
fi
# Check CSR file
if [ -n "${CSR}" ] && [ ! -f "${CSR}" ]; then
printf "The specified certificate signing request file does not exist\n" >&2
_safe_exit 1
fi
# Interactive-only arguments
if [ -n "${INTERACT}" ]; then
# Country
if [ -z "${C}" ]; then
printf "Country Name (2 letter code) [AU]: "
read -r C
fi
# State
if [ -z "${ST}" ]; then
printf "State or Province Name (full name) [Some-State]: "
read -r ST
fi
# Locality
if [ -z "${L}" ]; then
printf "Locality Name (eg, city) []: "
read -r L
fi
# Organization
if [ -z "${O}" ]; then
printf "Organization Name (eg, company) [Internet Widgits Pty Ltd]: "
read -r O
fi
# Organizational Unit
if [ -z "${OU}" ]; then
printf "Organizational Unit Name (eg, section) []: "
read -r OU
fi
fi
# Common Name
# This field is required and will ignore interactive rules
if [ -z "${CN}" ]; then
printf "Common Name (e.g. server FQDN or YOUR name) []: "
read -r CN
fi
# File name used for generating files
FILE="${CN/\*\./}"
# Build subject alternative names
_build_san
# Email Address
if [ -z "${EMAIL}" ] && [ -n "${INTERACT}" ]; then
printf "Email Address []: "
read -r EMAIL
fi
# Make sure output directory ends with a directory separator
if [ "${OUT: -1}" != "/" ]; then
OUT="${OUT}/"
fi
# Check if output directory exists
if [ ! -d "${OUT}" ]; then
if [ -n "${CREATE_PATH}" ]; then
# Create path
mkdir -p "${OUT}"
else
# Report non-existent path
printf "The specified directory '%s' does not exist\n" "${OUT}" >&2
_safe_exit 1
fi
fi
# Build certificate subject
_build_subj
# Validate extfile if provided
if [ -n "${EXTFILE}" ] && [ ! -f "${EXTFILE}" ]; then
printf "The specified extfile '%s' does not exist\n" "${EXTFILE}" >&2
_safe_exit 1
fi
}
#######################################
# Trust certificate authority on Linux system
# Arguments:
# Command (string)
# Directory (string)
#######################################
_trust_linux() {
# If command and directory exist
if [ -n "$(command -v "$1")" ] && [ -d "$(dirname "$2")" ]; then
printf "Installing certificate authority (requires sudo privileges)\n"
# Add certificate if it doesn't exist & trust it
[ -f "$2" ] || sudo cp "${CA}" "$2" \
&& sudo "$1" \
&& return
fi
return 1
}
#######################################
# Trust certificate authority
# Globals:
# OSTYPE
# Arguments:
# None
#######################################
_trust_ca() {
# Check if CA exists and script is instructed to trust
if [ -f "${CA}" ] && [ -n "${TRUST}" ]; then
if [[ "${OSTYPE}" == "darwin"* ]]; then
# MacOS (Darwin)
sudo security add-trusted-cert -d -r trustRoot \
-k "/Library/Keychains/System.keychain" \
"${CA}" \
&& return
elif [[ "${OSTYPE}" == "linux"* ]]; then
# Linux (Fedora/CentOS, Debian/Ubuntu)
_trust_linux "update-ca-trust" "/etc/pki/ca-trust/source/anchors/${FILE}-ca.pem" \
|| _trust_linux "update-ca-certificates" "/usr/local/share/ca-certificates/${FILE}-ca.crt" \
&& return
fi
# Unsupported OS
printf "Error occurred while trusting certificate for OSTYPE '%s'\n" "${OSTYPE:-undefined}" >&2
printf "Please ensure you are on a supported system and have the required packages installed.\n" >&2
EXIT_CODE=1
fi
}
#######################################
# Generate certificate authority
# Arguments:
# None
#######################################
_build_ca() {
# Return early if CA args are provided or only generating CSR
if [ -n "${CA}" ] && [ -n "${CA_KEY}" ] || [ -n "${CSR_ONLY}" ]; then
return
fi
printf "Building certificate authority\n"
CA_KEY="${OUT}CA.key"
CA="${OUT}CA.pem"
# Use existing CA in current directory
if [ -f "${CA_KEY}" ] && [ -f "${CA}" ]; then
return
fi
EXT=""
if [ -n "${CA_EXT}" ]; then
EXT="-extensions ${CA_EXT}"
fi
# Generate certificate authority files
openssl genrsa -out "${CA_KEY}" "${BITS}"
openssl req -new -nodes -x509 -sha256 \
$(printf "%s" "${EXT}") \
-subj "${SUBJ}" \
-days "${DAYS}" \
-key "${CA_KEY}" \
-out "${CA}"
}
#######################################
# Generate certificate signing request
# Arguments:
# None
#######################################
_build_csr() {
# Return early if only building CA
if [ -n "${CA_ONLY}" ] || [ -f "${CSR}" ]; then
return
fi
# Point to generated CSR file
CSR="${OUT}${FILE}.csr"
# Generate key and certificate signing request
openssl genrsa -out "${OUT}${FILE}.key" "${BITS}"
openssl req -new -nodes -sha256 \
-subj "${SUBJ}" \
-newkey "rsa:${BITS}" \
-key "${OUT}${FILE}.key" \
-out "${CSR}"
}
#######################################
# Generate signed certificate
# Arguments:
# None
#######################################
_build_cert() {
# Return early if only building CA or CSR
if [ -n "${CA_ONLY}" ] || [ -n "${CSR_ONLY}" ]; then
return
fi
# Build extensions file if not provided
EXT="${EXTFILE}"
if [ ! -f "${EXTFILE}" ]; then
EXT="${OUT}${FILE}.ext"
cat > "${EXT}" <<EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
${SAN}
EOF
fi
# Create a signed certificate
openssl x509 -req -sha256 -CAcreateserial \
-CA "${CA}" \
-CAkey "${CA_KEY}" \
-days "${DAYS}" \
-extfile "${EXT}" \
-in "${CSR}" \
-out "${OUT}${FILE}.crt"
# Cleanup generated extensions file
if [ ! -f "${EXTFILE}" ]; then
rm -f "${EXT}"
fi
}
#######################################
# Order of execution
#######################################
_parse_args "$@"
_check_requirements
_validate_args
_build_ca
_trust_ca
_build_csr
_build_cert
#######################################
# Exit with code
#######################################
_safe_exit $EXIT_CODE