-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathssl_audit
498 lines (432 loc) · 15.9 KB
/
ssl_audit
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
#!/bin/bash
# ssl_audit
# Locate and report on SSL certs on a Linux or Solaris system
# Author: Rawiri Blundell, Datacom Compute
# Copyright: (c) MIT License
# Date: 20190702
###############################################################################
# Dynamically build PATH to ensure that locally installed binaries are found
# Blank a variable for the following dynamic PATH task
new_path=
# Iterate through a list of potential PATH members and add any found paths to
# the 'new_path' variable. This is mosly for the benefit of Solaris.
for dir in /usr/gnu/bin /usr/xpg6/bin /usr/xpg4/bin /usr/kerberos/bin \
/usr/kerberos/sbin /bin /sbin /usr/bin /usr/sbin /usr/contrib/bin \
/usr/local/bin /usr/local/sbin /opt/csw/bin /opt/csw/sbin /opt/sfw/bin \
/opt/sfw/sbin /usr/pkg/bin /usr/sfw/bin /usr/sfw/sbin /snap/bin; do
[[ -d "${dir}" ]] && new_path="${new_path}:${dir}"
done
# Now assign our freshly built new_path variable, removing any leading colon
PATH="${new_path#:}"
# Finally, export the PATH and unset new_path
export PATH
unset -v new_path
# If HOSTNAME isn't set, then set it
if [[ ! "${HOSTNAME}" ]]; then
HOSTNAME=$(hostname); readonly HOSTNAME; export HOSTNAME
fi
# Trap all exit types to ensure that any temp files are removed
trap "rm -rf /tmp/ssl_report 2>/dev/null" EXIT
# Expected format example: "Nov 10 2034 21:19:01"
convert_time_to_epoch() {
local month day timestamp year hours min sec
# Read our incoming date/time information into our variables
read -r month day year timestamp < <(echo "${*:?No date provided}")
IFS=':' read -r hours min sec < <(echo "${timestamp}")
# Convert the month to 0..11 range
case "${month}" in
([jJ]an*) month=0 ;;
([fF]eb*) month=1 ;;
([mM]ar*) month=2 ;;
([aA]pr*) month=3 ;;
([mM]ay) month=4 ;;
([jJ]un*) month=5 ;;
([jJ]ul*) month=6 ;;
([aA]ug*) month=7 ;;
([sS]ep*) month=8 ;;
([oO]ct*) month=9 ;;
([nN]ov*) month=10 ;;
([dD]ec*) month=11 ;;
esac
# Pass our variables to the mighty 'perl'
perl -e 'use Time::Local; print timegm(@ARGV[0,1,2,3,4], $ARGV[5]-1900)."\n";' "${sec}" "${min}" "${hours}" "${day}" "${month}" "${year}"
}
extract_cert_bundle() {
awk '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/{ if(/BEGIN/){a++}; out="cert"a".pem"; print >out}' "${1:?No Cert Defined}"
}
# Try to convert a relative path to an absolute one
# A slightly adjusted version sourced from https://stackoverflow.com/a/21188136
get_absolute_path() {
_filename="${1}"
_parentdir=$(dirname "${_filename}")
# We only act further if the file actually exists
[ -e "${_filename}" ] || return 1
if [ -d "${_filename}" ]; then
printf -- '%s\n' "$(cd "${_filename}" && pwd)"
elif [ -d "${_parentdir}" ]; then
printf -- '%s\n' "$(cd "${_parentdir}" && pwd)/$(basename "${_filename}")"
fi
unset -v _filename _parentdir
}
# date +%s is not portable, so we provide this function
# To do this in pure shell is... fun... however 'perl' is assumed
# elsewhere in this script, so we may as well depend on that for our failover option
if date +%s 2>/dev/null | grep '%s' >/dev/null 2>&1; then
get_epoch() { perl -e 'print time."\n";'; }
else
get_epoch() { date +%s; }
fi
# We provide a function to try to determine if a cert is provided by a package
if command -v dpkg >/dev/null 2>&1; then
get_file_provider() {
dpkg -S "${1:?No file defined}" 2>/dev/null | awk -F ':' '{print $1}'
}
elif command -v rpm >/dev/null 2>&1; then
get_file_provider() {
read -r < <(rpm -qf "${1:?No file defined}" 2>/dev/null)
case "${REPLY}" in
(*'not owned'*) : ;;
(*) printf -- '%s\n' "${REPLY}" ;;
esac
}
elif command -v pkgchk >/dev/null 2>&1; then
# shellcheck disable=SC2119
get_file_provider() {
pkgchk -l -p "${1:?No file defined}" |
sed '1,/Referenced by the following/d;/Current status/,$d' |
trim |
paste -sd "," -
}
else
get_file_provider() {
printf -- '%s\n' "UNKNOWN"
}
fi
# Let's setup the following, somewhat obvious functions
get_file_size() {
stat -c %s "${1:?No Target Defined}" 2>/dev/null ||
perl -e 'if (! -f $ARGV[0]){die "0000000"};$size=(stat($ARGV[0]))[7];print $size."\n";' "${1:?No Target Defined}"
}
is_directory() {
[[ -d "${1:?No Directory Defined}" ]]
}
is_fsobj() {
[[ -r "${1:?No Cert Defined}" ]]
}
is_symlink() {
[[ -L "${1:?No Cert Defined}" ]]
}
# A portability function for older systems that don't have the mapfile builtin
if ! command -v mapfile >/dev/null 2>&1; then
mapfile() {
local _array_name i IFS
unset MAPFILE
set -f # Turn off globbing
set +H # Prevent parsing of '!' via history substitution
# We use the behaviour of '-t' by default, so if it's given, skip it
while getopts ":t" flags; do
case "${flags}" in
(t) :;; # Only here for compatibility
(*) :;; # Dummy action
esac
done
shift "$(( OPTIND - 1 ))"
# If an argument is left, it's our array name, otherwise this
# function will export an array named MAPFILE (as the real 'mapfile' does)
_array_name="${1}"
# Read all of the input
i=0
while IFS=$'\n' read -r; do
MAPFILE[i]="${REPLY}"
((i++))
done
# Sometimes there's a trailing line in a while read loop, if so catch it
[[ "${REPLY}" ]] && MAPFILE[i]="${REPLY}"
export MAPFILE
# Finally, rename the array if required
# I would love to know a better way to handle this
if [[ -n "${_array_name}" ]]; then
# shellcheck disable=SC2034
eval "${_array_name}=( \"\${MAPFILE[@]}\" )"
fi
# Set f and H back to normal
set +f
set -H
}
fi
# A function to remove whitespace either side of an input
# May require further testing and development
# shellcheck disable=SC2120
trim() {
LC_CTYPE=C
local outLn=""
# If $1 is a readable file OR if $1 is blank, we process line by line
# Because we assign a variable, leading and trailing whitespace is stripped
if [[ -r "${1}" ]]||[[ -z "${1}" ]]; then
while read -r outLn; do
printf -- '%s\n' "${outLn}"
done < "${1:-/dev/stdin}"
# Otherwise, we process whatever input arg(s) have been supplied
else
local readLn="${*}"
while true; do
outLn="${readLn#[[:space:]]}" # Strip whitespace to the left
outLn="${outLn%[[:space:]]}" # Strip whitespace to the right
[[ "${outLn}" = "${readLn}" ]] && break
readLn="${outLn}"
done
printf -- '%s\n' "${outLn}"
fi
}
print_header() {
printf -- '%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n' \
"Hostname" \
"File Path" \
"Common Name" \
"Not Before" \
"Not After" \
"Serial" \
"Issuer" \
"Algorithm" \
"Fingerprint" \
"Expiry State" \
"Days Left" \
"subjectAltNames" \
"ouName" \
"email address" \
"Source package"
}
# I know that the functions below result in multiple calls to openssl
# This is computationally inefficient, but it's just how this script grew
read_cert() {
openssl x509 -in "${1:?No Cert Defined}" -text -noout
}
read_cert_active() {
openssl x509 -in "${1:?No Cert Defined}" -startdate -noout |
sed -e "s/^notBefore=//" -e "s/GMT//" |
awk '{printf("%s %02d %d %s\n", $1,$2,$4,$3)}'
}
read_cert_algorithm() {
local cert_algorithm
cert_algorithm=$(read_cert "${1:?No Cert Defined}" |
awk -F ': ' '/Signature Algorithm/{print $2; exit}')
# Sometimes openssl isn't new enough to recognise a human friendly name
# and returns an oid instead. We map these cases here,
# reference: http://oid-info.com
case "${cert_algorithm}" in
('1.2.840.10045.4.3.1') cert_algorithm="ecdsa-with-SHA224" ;;
('1.2.840.10045.4.3.2') cert_algorithm="ecdsa-with-SHA256" ;;
('1.2.840.10045.4.3.3') cert_algorithm="ecdsa-with-SHA384" ;;
('1.2.840.10045.4.3.4') cert_algorithm="ecdsa-with-SHA512" ;;
(*) : ;;
esac
printf -- '%s\n' "${cert_algorithm}"
}
read_cert_cn() {
openssl x509 -in "${1:?No Cert Defined}" -subject -noout -nameopt multiline |
awk -F '= ' '/commonName/{print $2}' |
paste -sd "," -
}
read_cert_email() {
openssl x509 -in "${1:?No Cert Defined}" -subject -noout -nameopt multiline |
awk -F '= ' '/emailAddress/{print $2}'
}
read_cert_expiry() {
openssl x509 -in "${1:?No Cert Defined}" -enddate -noout |
sed -e "s/^notAfter=//" -e "s/GMT//" |
awk '{printf("%s %02d %d %s\n", $1,$2,$4,$3)}'
}
read_cert_issuer() {
openssl x509 -in "${1:?No Cert Defined}" -issuer -noout |
sed -e "s/^issuer=//"
}
read_cert_ou_name() {
openssl x509 -in "${1:?No Cert Defined}" -subject -noout -nameopt multiline |
awk -F '= ' '/organizationalUnitName/{print $2}' |
paste -s -
}
# shellcheck disable=SC2119
read_cert_sans() {
openssl x509 -in "${1:?No Cert Defined}" -text -noout |
grep "DNS:" |
trim |
paste -sd ' ' - |
grep .
}
read_cert_serial() {
openssl x509 -in "${1:?No Cert Defined}" -serial -noout |
sed -e "s/^serial=//"
}
read_cert_state() {
case "$(openssl x509 -in "${1:?No Cert Defined}" -checkend "${2:-0}")" in
(*'not expire'*) printf -- '%s\n' "OK" ;;
(*'will expire') printf -- '%s\n' "EXPIRED" ;;
esac
}
read_cert_fingerprint() {
openssl x509 -in "${1:?No Cert Defined}" -fingerprint -noout
}
# Calculate how many days until the cert expires
# Short circuit versions of 'date' that don't support '-d' (e.g. Solaris)
# In this instance, we want to call 'convert_time_to_epoch()'
if date -d yesterday 2>&1 | grep -E 'illegal|usage' >/dev/null 2>&1; then
calculate_cert_epoch() {
convert_time_to_epoch "$(read_cert_expiry "${1:?No Cert Defined}")"
}
else
calculate_cert_epoch() {
date -d "$(read_cert_expiry "${1:?No Cert Defined}")" +%s
}
fi
calculate_cert_expiry() {
local cert_epoch
cur_epoch=$(get_epoch)
cert_epoch=$(calculate_cert_epoch "${1:?No Cert Defined}")
printf -- '%s\n' "$(( ( cert_epoch - cur_epoch ) / 86400 )) days"
}
###############################################################################
# First, we look to the script's positional parameters.
# If a path to a particular cert is given, we just want to audit that
# If a path is given with -a, we append it to the system-wide audit
# Otherwise, we just perform a system-wide audit
case "${1}" in
(-a)
built_in=true
[[ -r "${2}" ]] && append_path="$(get_absolute_path "${2}")"
;;
('')
built_in=true
;;
(*)
built_in=false
is_fsobj "${1}" ||
{ printf -- '%s\n' "${1} does not exist or isn't readable" >&2; exit 1; }
cert_pathlist=( "$(get_absolute_path "${1}")" )
;;
esac
if [[ "${built_in}" = "true" ]]; then
# builtin list of potential paths, please feel free to submit additions!
# The default list is sourced from golang's cert detection:
# https://golang.org/src/crypto/x509/root_linux.go
cert_pathlist=(
/etc/ssl/certs/ca-certificates.crt
/etc/pki/tls/certs/ca-bundle.crt
/etc/ssl/ca-bundle.pem
/etc/pki/tls/cacert.pem
/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
/usr/local/share/ca-certificates
/etc/ssl/private
)
# Possible additions from elsewhere in golang
# "/etc/ssl/certs", // SLES10/SLES11, https://golang.org/issue/12139
# "/system/etc/security/cacerts", // Android
# "/usr/local/share/certs", // FreeBSD
# "/etc/pki/tls/certs", // Fedora/RHEL
# "/etc/openssl/certs", // NetBSD
# If append_path is set, add it to the array
if [[ "${append_path}" ]]; then
cert_pathlist=( "${cert_pathlist[@]}" "${append_path}" )
fi
# Use mlocate to identify any other potential certs
if command -v locate &>/dev/null; then
while read -r; do
cert_pathlist=( "${cert_pathlist[@]}" "${REPLY}" )
done < <(locate -r ".*\\.\\(crt\\|cer\\|der\\|jdb\\|jks\\|keystore\\|p7b\\|p7c\\|p12\\|pem\\|pfx\\|ss0\\)$" 2>/dev/null)
fi
# And/or simple-locate, if it's present
if [[ -r /var/lib/simple-locate/locate.root ]]; then
while read -r; do
cert_pathlist=( "${cert_pathlist[@]}" "${REPLY}" )
done < <(grep -E "\\.(crt|cer|der|jdb|jks|keystore|p7b|p7c|p12|pem|pfx|ss0)$" /var/lib/simple-locate/locate.root 2>/dev/null)
fi
fi
# We expand directories and resolve symlinks
for cert_path in "${cert_pathlist[@]}"; do
if is_directory "${cert_path}"; then
while read -r; do
cert_pathlist=( "${cert_pathlist[@]}" "${REPLY}" )
done < <(find "${cert_path}" -type f)
mapfile -t cert_pathlist < <(printf -- '%s\n' "${cert_pathlist[@]}" | grep -v "^${cert_path}$" | grep .)
fi
# If it's a symlink, translate it to its target path
# Remove the symlink and add the target to the array
if is_symlink "${cert_path}"; then
actualcert_path=$(readlink -f "${cert_path}")
cert_pathlist=( "${cert_pathlist[@]}" "${actualcert_path}" )
mapfile -t cert_pathlist < <(printf -- '%s\n' "${cert_pathlist[@]}" | grep -v "^${cert_path}$" | grep .)
fi
done
# Now let's de-duplicate and de-gap the array
mapfile -t cert_pathlist < <(printf -- '%s\n' "${cert_pathlist[@]}" | grep . | sort | uniq)
# Print our header
print_header
# Now let's sanity check each path in the array through multiple passes
# First, we check for directories and expand their contents into the array
for cert_path in "${cert_pathlist[@]}"; do
# If we hit an empty element, skip to the next one
[[ -z "${cert_path}" ]] && continue
# If it doesn't exist, skip to the next one
! is_fsobj "${cert_path}" && continue
# If it's 0-sized, skip to the next one
(( $(get_file_size "${cert_path}") == 0 )) && continue
# If we're not able to read it, let stderr know and skip to the next one
if read_cert "${cert_path}" 2>&1 | grep -q "unable to load certificate"; then
printf -- '%s\n' "Unable to read '${HOSTNAME}:${cert_path}' for some reason" >&2
continue
fi
cert_pkg=$(get_file_provider "${cert_path}")
# Once all of that is FINALLY sorted out, let's process it
# We want to output CSV format with the following details
# hostname; file path; common name; active date; expiry date; cert serial;
# cert issuer; cert algorithm; fingerprint; expiry state;
# days since/until expiry; sans; ou; email
# shellcheck disable=SC2126
cert_count=$(grep -E '\-BEGIN CERTIFICATE\-' "${cert_path}" | wc -l)
if (( cert_count == 1 )); then
printf -- '%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n' \
"${HOSTNAME}" \
"${cert_path}" \
"$(read_cert_cn "${cert_path}")" \
"$(read_cert_active "${cert_path}")" \
"$(read_cert_expiry "${cert_path}")" \
"$(read_cert_serial "${cert_path}")" \
"$(read_cert_issuer "${cert_path}")" \
"$(read_cert_algorithm "${cert_path}")" \
"$(read_cert_fingerprint "${cert_path}")" \
"$(read_cert_state "${cert_path}")" \
"$(calculate_cert_expiry "${cert_path}")" \
"$(read_cert_sans "${cert_path}")" \
"$(read_cert_ou_name "${cert_path}")" \
"$(read_cert_email "${cert_path}")" \
"${cert_pkg:--}"
else
cert_tmpdir="/tmp/ssl_report/$(basename "${cert_path}")"
mkdir -p "${cert_tmpdir}"
(
cd "${cert_tmpdir}" || return 1
extract_cert_bundle "${cert_path}"
for cert_tmpfile in *; do
# If we're not able to read it, let stderr know and skip to the next one
if read_cert "${cert_tmpfile}" 2>&1 | grep -q "unable to load certificate"; then
continue
fi
printf -- '%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n' \
"${HOSTNAME}" \
"${cert_path}" \
"$(read_cert_cn "${cert_tmpfile}")" \
"$(read_cert_active "${cert_tmpfile}")" \
"$(read_cert_expiry "${cert_tmpfile}")" \
"$(read_cert_serial "${cert_tmpfile}")" \
"$(read_cert_issuer "${cert_tmpfile}")" \
"$(read_cert_algorithm "${cert_tmpfile}")" \
"$(read_cert_fingerprint "${cert_tmpfile}")" \
"$(read_cert_state "${cert_tmpfile}")" \
"$(calculate_cert_expiry "${cert_tmpfile}")" \
"$(read_cert_sans "${cert_tmpfile}")" \
"$(read_cert_ou_name "${cert_tmpfile}")" \
"$(read_cert_email "${cert_tmpfile}")" \
"${cert_pkg:--}"
done
)
fi
done