cm.sh 26 KB
Newer Older
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env bash
# ======================================================================
#
# WRAPPER FOR ACME.SH 
# Let's Encrypt client
#
# requires
# - bash
# - openssl
# - curl
# - dig (opional)
# - acme.sh client
#
# ----------------------------------------------------------------------
15
16
# 2021-02-02  <axel.hahn@iml.unibe.ch>  first lines
# 2021-02-10  <axel.hahn@iml.unibe.ch>  compare hashes, logging
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
17
# 2021-02-12  <axel.hahn@iml.unibe.ch>  added self test
18
# 2021-02-17  <axel.hahn@iml.unibe.ch>  ensure checks list of aliases; new: optional host filter before adding a cert
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
19
# 2021-03-12  <axel.hahn@iml.unibe.ch>  create file for haproxy
20
# 2021-03-22  <axel.hahn@iml.unibe.ch>  for haproxy: use chained cert instead of server cert
21
# 2021-04-12  <axel.hahn@iml.unibe.ch>  reject multiple usage of fqdn in cli params
22
# 2021-04-12  <axel.hahn@iml.unibe.ch>  optional: force excecution with a given user only
23
# 2021-06-24  <axel.hahn@iml.unibe.ch>  added transfer command; delete files if acme.sh --install-cert ... failes
24
# 2021-07-14  <axel.hahn@iml.unibe.ch>  added _wait_for_free_slot in cert actions to execute multiple processes sequentially
25
# 2021-09-27  <axel.hahn@iml.unibe.ch>  softer behaviour: do not revoke changed certs (add does not stop; ensure does not delete)
26
# 2021-12-23  <axel.hahn@iml.unibe.ch>  added param --trace as 1st param to generate a trace log 
27
# 2022-01-10  <axel.hahn@iml.unibe.ch>  _wait_for_free_slot: exclude ssh calls 
28
# 2022-03-30  <axel.hahn@iml.unibe.ch>  remove usage of csr and generation of key file
29
# 2022-03-31  <axel.hahn@iml.unibe.ch>  dns authentication with alias domain
30
# 2022-04-04  <axel.hahn@iml.unibe.ch>  Bugfix: copy key from csr folder to ~/.acme/
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
31
# 2022-04-04  <axel.hahn@iml.unibe.ch>  added param "list-old"
32
# 2022-04-07  <axel.hahn@iml.unibe.ch>  fix missing key in public_ensure before calling public_add too.
33
# 2022-04-20  <axel.hahn@iml.unibe.ch>  fix multiple domains using domain alias
34
# 2022-04-21  <axel.hahn@iml.unibe.ch>  mix multiple domains using domain alias or not
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
35
# 2022-05-19  <axel.hahn@iml.unibe.ch>  add timer and debug.log
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
36
37
38
39
40
41
42
43
44
# ======================================================================


# ----------------------------------------------------------------------
#
# CONFIG
#
# ----------------------------------------------------------------------

45
46
47
logdir="./log"
touchfile="$logdir/lastchange.txt"
logfile="$logdir/certmanager.log"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
48
debuglogfile="$logdir/debug.log"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
49

50
51
# CSR USAGE WAS REMOVED
# csrfile="./templates/csr.txt"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
52

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
53
line="_______________________________________________________________________________"
54

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
55
56
# flag: show debug infos on console (STDOUT)
CM_showdebug=0
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
57

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
58
59
60
61
62
63
64
# flag: write a log for created/ renewd/ deleted certs
CM_writelog=1

# flag: write a log for executed functions with timer and process count
CM_writedebuglog=0

CM_timer_start=$( date +%s.%N )
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
65
66
67
68
69
70
71

# ----------------------------------------------------------------------
#
# INTERNAL FUNCTIONS
#
# ----------------------------------------------------------------------

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# BUGFIX: acme.sh does not create a new key file on renew.
# After switching from csr method to param -d we got a 0 byte Keyfile
function _fixKeyfile(){
	local _acme_keyfile=~/.acme.sh/${CM_fqdn}/${CM_fqdn}.key
	if test ! -f "$_acme_keyfile"
	then
		echo "FIX: copy key from csr folder $CM_filekey to $_acme_keyfile"
		if ! cp "$CM_filekey" "$_acme_keyfile"
		then
			exit 1
		fi
	fi

}

87
88
89
90
91
# internal function; list certificates incl. creation date and renew date
function _listCerts(){
	$ACME --list	
}

92
93
94
95
96
# internal function; get a list of fqdn of all existing certs
function _listCertdomains(){
	_listCerts | sed -n '2,$p' | awk '{ print $1 }'
}

97
98
99
# internal function; checks if a certificate for a given FQDN already exists
# used in _certMustExist, _certMustNotExist
# param  string  FQDN
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
100
function _certExists(){
101
	_listCertdomains | grep "^${CM_fqdn}$" >/dev/null
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
102
103
}

104
105
106
# internal function; a certificate of a given FQDN must exist - otherwise
# the script will be aborted
# param  string  FQDN
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
107
108
109
110
111
112
113
function _certMustExist(){
	_certExists
	if [ $? -ne 0 ]; then
		echo "ERROR: cert ${CM_fqdn} was not added yet."
		exit 1
	fi
}
114
115
116
117

# internal function; a certificate of a given FQDN must not exist - otherwise
# the script will be aborted
# param  string  FQDN
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
118
function _certMustNotExist(){
119
120
121
	if _certExists
	then
		echo "ERROR: cert ${CM_fqdn} was added already."
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
122
123
124
		# exit 1
		echo "Press Ctrl+C to abort within the next 10 sec..."
		sleep 10
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
125
126
127
128
	fi
}

# internal function: transfer generated/ updated cert data to a
129
# known directory (based on CM_diracme - see inc_config.sh)
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
130
# used in public_add and public_renew
131
# used in ADD and RENEW action
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
132
function _certTransfer(){
133
	_wd "--- acme internal data - ~/.acme.sh/${CM_fqdn}"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
134
135
	ls -l ~/.acme.sh/${CM_fqdn}

136
137
138
139
	_wd "--- delete current files in ${CM_dircerts}/ if they already exist."
    test -d ${CM_dircerts} && rm -f "${CM_dircerts}/*" 2>/dev/null

	_wd "--- transfer acme.sh files to ${CM_dircerts}/"
140
	if ! $ACME \
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
141
		--install-cert \
142
143
144
145
146
147
148
		-d "${CM_fqdn}" \
		--key-file        "${CM_outfile_key}"   \
		--cert-file       "${CM_outfile_cert}"  \
		--fullchain-file  "${CM_outfile_chain}" \
		--ca-file         "${CM_outfile_ca}"
    then
        echo "ERROR occured during acme transfer. Removing files in ${CM_dircerts} to prevent strange effects..."
149
        rm -f "${CM_dircerts}/*"
150
        exit 2
151
152
153
    fi
	echo "OK."
	
154
155
	# _wd "--- copy key to ${CM_dircerts}"
	# cp ${CM_filekey} ${CM_outfile_key}
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
156

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
157
	_wd "--- create chained file for haproxy"
158
	cat "${CM_outfile_chain}" "${CM_outfile_key}" > "${CM_outfile_haproxy}"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
159

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
160
	_wd "--- content of output dir $CM_dircerts:"
161
162
163
164
165
166
	if ! ls -l "${CM_outfile_cert}" "${CM_outfile_chain}" "${CM_outfile_key}" "${CM_outfile_haproxy}"
    then
        echo "ERROR missing a file (or no access?)"
        rm -f "${CM_dircerts}/*"
        exit 2
    fi
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
167
168
}

169
# internal function; show md5 hashsums for certificate and key
170
171
# for visual comparison if the match
function _certMatching(){
172
	# CSR USAGE WAS REMOVED
173
	# local md5_csr=$(  test -f ${CM_filecsr}      && openssl req  -noout -modulus -in ${CM_filecsr}      | openssl md5 | cut -f 2 -d " " )
174
175
	local md5_key=$(  test -f ${CM_outfile_key}  && openssl rsa  -noout -modulus -in ${CM_outfile_key}  | openssl md5 | cut -f 2 -d " " )
	local md5_cert=$( test -f ${CM_outfile_cert} && openssl x509 -noout -modulus -in ${CM_outfile_cert} | openssl md5 | cut -f 2 -d " " )
176

177
	echo
178
	echo "--- compare hashes"
179
	# CSR USAGE WAS REMOVED
180
	# echo "csr  : $md5_csr (used for creation of cert)"
181
	echo "key  : $md5_key"
182
183
184
	echo "cert : $md5_cert"
	if [ "$md5_key" = "$md5_cert" ]; then
		echo "OK, key and cert match :-)"
185
	else
186
		echo "ERROR: key and cert do NOT MATCH!"
187
	fi
188
189
	echo
}
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
190
191
192
193

# internal function: dig for given fqdn.
# Function stops if fqdn was not found in DNS.
# If dig is not found the function skips the DNS check.
194
# This function is used in _dnsCheck
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
195
# param  string  fqdn to check
196
# param  string  type of dns entry; one of a|cname
197
# param  string  optional filter on output of dig (regex)
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
198
199
function _checkDig(){
    local myfqdn=$1
200
	local _type=${2:-"a"}
201
	local _verify=${3:-"."}
202
203
204
205

    if which dig >/dev/null
    then
        # _wd "[$myfqdn] exists as type [$_type] in DNS?"
206
        if ! dig "${myfqdn}" "${_type}" | grep "^${myfqdn}" | grep -E "${_verify}"
207
208
        then
            echo "ERROR: [$myfqdn] was not found. Maybe there is a typo in the hostname or it does not exist in DNS."
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
209
210
            exit 2
        fi
211
        _wd "OK: [$myfqdn] exists in DNS."
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
212
213
214
215
216
217
218
    else
        _wd "SKIP: dig was not found"
    fi
    echo

}

219
220
221
222
223
224
# internal function: check DNS entries
# - the hostname to be added in the certificate must exist
# - if a hostname does not match and CM_challenge_alias was set:
#   - _acme-challenge.FQDN must be a cname to _acme-challenge.${CM_challenge_alias}
# Function stops if a fqdn was not found in DNS.
# param  string  fqdn(s) that are part of the certificate
225
function _dnsCheck(){
226
227
228
229
	local altdns=
	local _mydomain=
	local _subdomain='_acme-challenge'

230
	for _mydomain in $*
231
232
	do
		_wd "dig check - domain for cert"
233
		_checkDig "$_mydomain" "a" "IN.*(A|CNAME)" # matches A and CNAME records
234

235
		if [ -n "${CM_challenge_alias}" ] && ! echo "$_mydomain" | grep "${CM_certmatch}" >/dev/null
236
		then
237
			_wd "dig check - cname ${_subdomain}.${_mydomain} must exist"
238
			_checkDig "${_subdomain}.${_mydomain}" "cname"
239
240
			_wd "dig check - cname ${_subdomain}.${_mydomain} must point to ${_subdomain}.${CM_challenge_alias}"
			_checkDig "${_subdomain}.${_mydomain}" "cname" "${_subdomain}.${CM_challenge_alias}"
241
242
243
		fi
	done

244
}
245

246
# CSR USAGE WAS REMOVED
247
248
# internal function; generate a csr file before creating a new certifcate
# this function is used in public_add
249
# function _UNUSED_gencsr(){
250

251
# 	local altdns=
252

253
254
255
256
257
258
259
# 	for myalt in $*
# 	do
# 		altdns="${altdns}DNS:$myalt,"
# 	done
# 	altdns=$( echo $altdns | sed "s#,\$##" )
#     _wd "--- $CM_fqdn"
# 	_wd "DNS alternative names: $altdns"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
260

261
262
# 	rm -f $CM_filecnf $CM_filekey $CM_filecsr
# 	mkdir -p "${CM_dircsr}" 2>/dev/null
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
263

264
265
266
267
# 	cat $csrfile \
# 		| sed "s#__FQDN__#$CM_fqdn#g"  		\
# 		| sed "s#__ALTNAMES__#$altdns#g"	\
# 		> $CM_filecnf || exit 1
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
268

269
270
271
# 	# generate csr
# 	_wd "creating key and csr"
# 	openssl req -new -config $CM_filecnf -keyout $CM_filekey -out $CM_filecsr || exit 1
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
272

273
274
275
276
# 	# view csr
# 	# openssl req -noout -text -in $CM_filecsr
# 	ls -ltr $CM_filecnf $CM_filekey $CM_filecsr
# }
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
277

278
279
280
281
282
283
284
285
286
287
288
# internal function; get a sorted list of DNS aliases in the current cert
function _getAliases(){
	_sortWords $(
		openssl x509 -noout -text -in ${CM_outfile_cert} \
			| grep -E "(DNS:)" \
			| sed "s#^\ *##g"  \
			| sed "s#DNS:##g"  \
			| sed "s#,##g"
	)
}

289
290
# internal function; check if a required 2nd CLI parameter was given
# if not the script will abort
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
291
292
293
294
295
296
297
function _requiresFqdn(){
	if [ -z "$CM_fqdn" ]; then
		echo "ERROR: 2nd parameter must be a FQDN for Main_Domain."
		exit 1
	fi
}

298
299
300
# internal function; it shows a message if the current instance uses a stage
# server. It shows a message that it is allowed to test arround ... or to be 
# careful with LE requests on a production system
301
302
303
function _testStaging(){
	echo $ACME_Params | grep "\-\-staging" >/dev/null
	if [ $? -eq 0 ]; then
304
		_wd "Using Let's Encrypt STAGE environment ..."
305
306
		_wd "You can test and mess around. Do not use certs in production."
	else
307
308
		_wd "Using Let's Encrypt LIVE environment for production."
		_wd "Be careful with count of connects to Let's Encrypt servers."
309
310
311
	fi
	echo
}
312
313
314
315
316
317
318
319
320
321
322
323
# internal function; if a user was set as CM_user then verify it with
# current user
function _testUser(){
	if [ ! -z "$CM_user" ]; then
		local _sUser=`id | cut -f 2 -d "(" | cut -f 1 -d ")"`
		if [[ $_sUser != "$CM_user" ]]; then
			echo "ERROR: Run this script under user [$CM_user] - not as $_sUser."
			exit 1
		fi
	fi

}
324

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# set update message into access log file
# global bool CM_writedebuglog flag to write access log.
# param  string(s)  message
function _debuglog(){
	if [ ${CM_writedebuglog} -eq 1 ]; then
		local _sProcesses
		typeset -i local _iProcesses
		typeset -i local _iPos
		_sProcesses=$( ps -ef | grep "bash.*$0" | grep -v "ssh.*@" | grep -v "grep" | sort -k 2 -n )
		_iProcesses=$( echo "$_sProcesses" | wc -l )
		_iPos=$( echo "$_sProcesses" | grep -n " $$ " | head -1 | cut -f 1 -d ':' )
		echo "$( date ) $CM_fqdn [$$] | $(show_timer) | pos $_iPos of $_iProcesses processes | $*" >> ${debuglogfile}
	fi
}


Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
341
342
343
# set update message in a file
# param  string(s)  message
function _update(){
344
	echo "[$( date )] $*" > ${touchfile}
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
345
	test ${CM_writelog} -ne 0 && echo "[$( date )] $*" >> ${logfile}
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
346
347
}

348
349
350
351
# "neverending" loop that waits until the current process is
# the one with lowest PID
function _wait_for_free_slot(){
    local _bWait=true
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
352
	_debuglog "start in _wait_for_free_slot"
353
    typeset -i local _iFirstPID=0
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
354
355
356
    local _sProcesses
	
	_wd "--- Need to wait until own process PID $$ is on top ... "
357
358
    while [ $_bWait = true ];
    do
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
359
360
361
362
		_sProcesses=$( ps -ef | grep "bash.*$0" | grep -v "ssh.*@" | grep -v "grep" | sort -k 2 -n )
        # _iFirstPID=$( ps -ef | grep "bash.*$0" | grep -v "ssh.*@" | grep -v "grep" | sort -k 2 -n | head -1 | awk '{ print $2}' )
        _iFirstPID=$( echo "$_sProcesses" | head -1 | awk '{ print $2}' )

363
364
365
366
367
        if [ $_iFirstPID -eq $$ ]; then
            _bWait=false
            _wd "OK. Go!"
        else
            _wd "- all instances"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
368
369
370
			_debuglog "waiting in _wait_for_free_slot"
            # test ${CM_showdebug} && ps -ef | grep "bash.*$0" | grep -v "ssh.*@" | grep -v "grep" | sort -k 2 -n
            test ${CM_showdebug} -ne 0 && echo "$_sProcesses"
371
372
373
            sleep 10
        fi
    done
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
374
	_debuglog "end _wait_for_free_slot"
375
376
}

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
377
# write debug output if CM_showdebug is set to 1
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
378
function _wd(){
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
379
	test ${CM_showdebug} -ne 0 && echo "DEBUG: $*"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
380
381
}

382
383
384
385
# set environment for a single certificate based on FQDN
# param  string  FQDN
function _setenv(){
	CM_fqdn=$1
386
387
	# CSR USAGE WAS REMOVED
	# keeping vars to delete files of existing certs that used a csr
388
389
390
391
392
393
394
395
	CM_filecsr="${CM_dircsr}/${CM_fqdn}.csr"
	CM_filecnf="${CM_dircsr}/${CM_fqdn}.cnf"
	CM_filekey="${CM_dircsr}/${CM_fqdn}.key"

	CM_dircerts="${CM_diracme}/${CM_fqdn}"
	CM_outfile_cert=${CM_dircerts}/${CM_fqdn}.cert.cer
	CM_outfile_chain=${CM_dircerts}/${CM_fqdn}.fullchain.cer
	CM_outfile_key=${CM_dircerts}/${CM_fqdn}.key.pem
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
396
	CM_outfile_haproxy=${CM_dircerts}/${CM_fqdn}.haproxy.pem
397
398
399
400
401
	CM_outfile_ca=${CM_dircerts}/${CM_fqdn}.ca.cer

	# echo $CM_fqdn; set | grep "^CM_"; echo

}
402
403
404
405
406
# internal function; helper: sort words in alphabetic order
function _sortWords(){
	echo $* | tr " " "\n" | sort | tr "\n" " "
}

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# internal function; verify fqdn in cli params - each fqdn is allowed only once.
# on error it shows the count of usage of each fqdn
function _testFqdncount(){
	typeset -i local iHostsInParam=$( echo $* | wc -w )
	typeset -i iHostsUniq=$( echo $* | tr " " "\n" | sort -u | wc -w )
	if [ $iHostsInParam -ne $iHostsUniq ]; then
		echo "ERROR: each given FQDN is allowed only once. You need to remove double entries."
		
		for myhost in $( echo $* | tr " " "\n" | sort -u )
		do
			typeset -i iHostcount=$( echo $* | tr " " "\n" | grep "^$myhost$" | wc -l )
			test $iHostcount -gt 1 && echo "  $iHostcount x $myhost"
		done
		echo
		exit 1
	fi
}
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438

# get time in sec and milliseconds since start
# no parameter is required
function show_timer(){
         local timer_end=$( date +%s.%N )
         local totaltime=$( awk "BEGIN {print $timer_end - $CM_timer_start }" )

         local sec_time=$( echo $totaltime | cut -f 1 -d "." )
         test -z "$sec_time" && sec_time=0

         local ms_time=$( echo $totaltime | cut -f 2 -d "." | cut -c 1-3 )

         echo "$sec_time.$ms_time sec"
}

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
439
440
441
442
443
444
445
446
447
448
# ----------------------------------------------------------------------
#
# PUBLIC FUNCTIONS
#
# ----------------------------------------------------------------------

#
# pulic function ADD certificate
# 
function public_add(){
449
450
	local _params=""

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
451
	_debuglog "start public_add"
452
453
454
455
	_wait_for_free_slot
	_requiresFqdn
    _certMustNotExist

456
	_dnsCheck $CM_fqdn $*
457
458
459

	for _mydomain in $CM_fqdn $*
	do
460
		_params+="-d $_mydomain --challenge-alias "
461
462
463

		if [ -n "${CM_challenge_alias}" ] && ! echo "$_mydomain" | grep "${CM_certmatch}" >/dev/null
		then
464
465
466
			_params+="${CM_challenge_alias} "
		else
			_params+="no "
467
468
469
470
471
472
473
		fi
	done

	_wd "--- create output dir $dircerts"
	mkdir -p "${CM_dircerts}" 2>/dev/null

	_wd "--- create certificate"
474
	echo "$ACME --issue $_params $ACME_Params"
475
476
477
478
479
480
481
482
483
484
485
486
	if ! $ACME --issue $_params $ACME_Params 
	then
		echo "ERROR: adding cert failed. Trying to delete internal data ..."
		public_delete $CM_fqdn
		exit 1
	fi
	# $ACME --issue -d $CM_fqdn $ACME_Params || exit 1

	_certTransfer
	_certMatching

	_update "added $CM_fqdn $*"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
487
	_debuglog "end public_add"
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
# CSR USAGE WAS REMOVED
# function OLD__public_add(){
# 	_wait_for_free_slot
# 	_requiresFqdn
#     _certMustNotExist

# 	for myhost in $( echo $CM_fqdn $*)
# 	do 
# 		echo $myhost | grep "$CM_certmatch" >/dev/null
# 		if [ $? -ne 0 ]; then
# 			echo "ERROR: host $myhost does not match [$CM_certmatch]."
# 			exit 1
# 		fi
# 	done
# 	_gencsr $CM_fqdn $*

# 	_wd "--- create output dir $dircerts"
# 	mkdir -p "${CM_dircerts}" 2>/dev/null

# 	_wd "--- csr data"
# 	$ACME --showcsr  --csr $CM_filecsr || exit 1

# 	_wd "--- create certificate"
# 	echo $ACME --signcsr --csr $CM_filecsr $ACME_Params 
# 	$ACME --signcsr --csr $CM_filecsr $ACME_Params 
# 	if [ $? -ne 0 ]; then
# 		echo "ERROR: adding cert failed. Trying to delete internal data ..."
# 		public_delete $CM_fqdn
# 		exit 1
# 	fi
# 	# $ACME --issue -d $CM_fqdn $ACME_Params || exit 1

# 	_certTransfer
# 	_certMatching

# 	_update "added $CM_fqdn $*"
# }
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
527

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
528
529
530
#
# pulic function ADD OR RENEW certificate
# 
531
function public_ensure(){
532
	_wait_for_free_slot
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
533
534
535
	_requiresFqdn
	_certExists
	if [ $? -eq 0 ]; then
536
537
538
539
540
541
542
543
544
545
		_wd "--- cert $CM_fqdn was found ... compare aliases"
		local _newAliases=$( _sortWords $CM_fqdn $* )
		local _certAliases=$( _getAliases )

		_wd "from params: $_newAliases"
		_wd "inside cert: $_certAliases"
		if [ "$_newAliases" = "$_certAliases" ]; then
			_wd "--- DNS aliases match ... renew it (ignore --force - it comes from acme.sh)"
			public_renew $*
		else
546
547
548
			# _wd "--- DNS aliases do NOT match ... deleting cert and create a new one"
			# public_delete $*
			_wd "--- DNS aliases do NOT match ... creating a new one"
549
			_fixKeyfile
550
551
			public_add $*
		fi
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
552
553
	else
		_wd "--- cert does mot exist ... add it"
554
		public_add $*
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
555
556
557
	fi
}

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
558
559
560
561
#
# public function to delete a cert
#
function public_delete(){
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
562
	_debuglog "start public_delete"
563
	_wait_for_free_slot
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
564
565
566
567
	_requiresFqdn
	_certMustExist

	# TODO: revoke it too??
568
	_wd "--- revoke cert"
569
	$ACME --revoke -d ${CM_fqdn} $ACME_Params
570
571
572
	_wd "--- delete ACME.SH data"
	$ACME --remove -d ${CM_fqdn} $ACME_Params
	_wd "--- delete local data"
573
574

	# CSR USAGE WAS REMOVED
575
	rm -rf ${CM_dircerts} ${CM_filecnf} ${CM_filekey} ${CM_filecsr} ~/.acme.sh/${CM_fqdn} && echo OK
576
	_update "deleted ${CM_fqdn}"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
577
	_debuglog "end public_delete"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
578
579
580
581
582
583
584
585
}


#
# public function; list certificates incl. creation date and renew date
# 
function public_list(){
	_listCerts
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602

}
#
# public function; list old / outdated certificates
# 
function public_list-old(){

	local _iRuntime=90
	local _iWarn=65
	typeset -i local _rc=0

	cd "${CM_dircerts}"  || exit 1

	echo
	echo "Cert dir is $( pwd )"
	echo
	echo "---- Certificates expiring soon - with age $_iWarn ... $_iRuntime days:"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
603
	if find -type f -name "*.cert.cer" -mtime +$_iWarn -mtime -$_iRuntime | grep . >/dev/null
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
604
	then
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
605
		find -type f -name "*.cert.cer" -mtime +$_iWarn -mtime -$_iRuntime  -exec ls -ld {} \; | nl
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
606
607
608
609
610
611
		_rc=1
	else 
		echo "     NONE."
	fi
	echo
	echo "---- Certificate list ... older $_iRuntime days:"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
612
	if find -type f -name "*.cert.cer" -mtime +$_iRuntime | grep . >/dev/null
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
613
	then
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
614
		find -type f -name "*.cert.cer" -mtime +$_iRuntime -exec ls -ld {} \; | nl
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
615
616
617
618
619
620
621
622
623
624
		_rc=2
	else
		echo "     NONE."
	fi

	echo	
	cd - >/dev/null

	_wd "Exiting with rc=$_rc"
	exit $_rc
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
625
626
}

627

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
628
629
630
631
#
# public function - renew a certificate
# param  string  fqdn of domain to renew
function public_renew(){
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
632
	_debuglog "start public_renew"
633
	_wait_for_free_slot
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
634
635
	_requiresFqdn
	_certMustExist
636

637
	_fixKeyfile
638

639
640
	$ACME --renew -d ${CM_fqdn} $ACME_Params
	local _rc=$?
641

642
643
644
645
646
647
648
649
650
651
652
653
654
	case $_rc in
		0)
			_certTransfer
			_certMatching
			_update "renewed ${CM_fqdn}"
			;;
		2)
			_wd "renew was skipped ... we need to wait a while."
			;;
		*)
			_wd "Error ocured."
			exit $_rc
	esac
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
655
	_debuglog "end public_renew"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
656
657
}

658
#
659
# public function - renew all certificates (to be used in a cronjob)
660
661
662
# no params
function public_renew-all(){

663
	_listCertdomains | while read mydomain
664
665
666
	do
		_wd "--- renew $mydomain"
		_setenv ${mydomain}
667
		public_renew
668
669
670
671
	done

}

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701

# internal function; helper for selftest to handle a single selftest
# if a given command is successful it shows "OK" or "ERROR" followed
# by the label inparam 2.
# The value _iErrors will be incremented by 1 if an error occured.
# param  string  command to verify
# param  string  output label
function _selftestItem(){
	local _check=$1
	local _label=$2
	local _status="OK:"

	eval "$_check"
	if [ $? -ne 0 ]; then
		_status="ERROR: the check failed for the test of -"
		_iErrors=$_iErrors+1
	fi

	echo "$_status $_label"
}

#
# list existing certs
# no params
function public_selftest(){

	typeset -i _iErrors=0

	echo
	echo --- dependencies
702
	_selftestItem "which openssl" "openssl was found"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
703
704
705
706
707
708
709
710
711
712
713
714
715
	_selftestItem "which curl" "curl was found"
	echo

	echo --- acme.sh client
	_selftestItem "ls -ld ${ACME}" "${ACME} exits"
	_selftestItem "test -x ${ACME}" "${ACME} is executable"
	echo

	echo --- acme.sh installation \(may fail in future releases of acme.sh\)
	_selftestItem "ls -ld ~/.acme.sh" "internal acme data were found = [acme.sh --install] was done"
	_selftestItem "test -w ~/.acme.sh/" "it is writable"
	echo

716
717
718
719
720
721
722
723
724
725
	# CSR USAGE WAS REMOVED
	# echo --- csr template
	# _selftestItem "ls -ld ${csrfile}"  "csr base template exists"
	# _selftestItem "test -r ${csrfile}" "it is readable"
	# echo
    #
	# echo --- output directory for csr and key
	# _selftestItem "ls -ld ${CM_dircsr}"  "data dir for csr exists"
	# _selftestItem "test -w ${CM_dircsr}" "it is writable"
	# echo
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745

	echo --- output dir for centralized place of certificates
	_selftestItem "ls -ld ${CM_diracme}"  "central output dir for certificate data exists"
	_selftestItem "test -w ${CM_diracme}" "it is writable"
	echo


	echo --- logs
	_selftestItem "ls -ld ./log/" "Logdir exists"
	_selftestItem "test -w" "Logdir is writable"
	test -f $logfile    &&  _selftestItem  "test -w $logfile" "Logfile $logfile is writable"
	test -f $touchfile  && _selftestItem "test -w $touchfile" "Logfile $touchfile is writable"
	echo

	echo --- Errors: $_iErrors
	test $_iErrors -eq 0 && echo "OK, this looks fine."
	echo
	exit $_iErrors
}

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
746
747
#
# list existing certs
748
# no params
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
749
750
751
752
function public_show(){
	_requiresFqdn
	_certMustExist

753
754
755
	# CSR USAGE WAS REMOVED
	# ls -l ${CM_filecsr} ${CM_dircerts}/*
	ls -l ${CM_dircerts}/*
756
	_certMatching
757
758
759
760
761

	# CSR USAGE WAS REMOVED
	# echo $line
	# echo CSR $CM_filecsr
	# openssl req -noout -text -in $CM_filecsr | grep -E "(Subject:|DNS:)" | sed "s#^\ *##g"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
762

763
764
765
766
767
768
769
	for myfile in ${CM_outfile_cert} ${CM_outfile_haproxy}
	do
        echo $line
        echo Cert ${myfile}
        # openssl x509 -noout -text -in ${CM_outfile_cert}
        openssl x509 -noout -text -in ${myfile} | grep -E "(Issuer:|Subject:|Not\ |DNS:)"| sed "s#^\ *##g"
    done
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
770
771
}

772
773
# Transfer cert from acme.sh internal cache to our output dir again
function public_transfer(){
774
	_wait_for_free_slot
775
776
777
778
779
	_requiresFqdn
	_certExists

	_certTransfer
}
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
780
781
782
783
784
785
786
787
788

# ----------------------------------------------------------------------
#
# main
#
# ----------------------------------------------------------------------

cd $( dirname $0 )

789
790
791
792
793
794
795
796
797
798
799
800
801
if [ "$1" = "--trace" ]; then
	tracelog="$logdir/trace__$2__$3__`date +%Y-%m-%d__%H-%M-%S`.log"
	exec  > >(tee -a ${tracelog}    )
	exec 2> >(tee -a ${tracelog} >&2)
	echo "TRACELOG was triggered."
	echo "TIME   : $(date)"
	echo "COMMAND: $0 $*"
	echo "LOG    : $tracelog"

	# set -vx
	shift 1
fi

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
cat <<ENDOFHEADER
$line


             	- - - ---===>>> CERT MANAGER <<<===--- - - -

$line

ENDOFHEADER

which openssl >/dev/null || exit 1

. ./inc_config.sh
if [ $? -ne 0 ]; then
	echo "ERROR: loading the config failed."
	echo "Copy the inc_config.sh.dist to inc_config.sh and make your settings in it."
	echo
	exit 1
fi

822
_testUser
823
_testStaging
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
824

825
826
827
test -z "${CM_diracme}" && CM_diracme=./certs
test -z "${CM_dircsr}"  && CM_dircsr=./csr

828
grep "function\ public_$1" $( basename $0 ) >/dev/null 
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
829
830
831
832
833
if [ $# -gt 0 -a $? -eq 0 ]; then
	# _wd $*
	action=$1
	CM_fqdn=$2
	shift 2
834

835
836
	_testFqdncount $CM_fqdn $*

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
837
838
839
840
841
842
	test -z "${ACME}" && ACME=$( which acme.sh )
	if [ ! -x "${ACME}" ]; then
		echo "ERROR: acme.sh not found. You need to install acme.sh client and configure it in inc_config.sh."
		exit 1
	fi

843
	_setenv $CM_fqdn
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
844
845

	_wd "A C T I O N -->> $action <<--"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
846
	_debuglog ">>> START public_$action $CM_fqdn $*"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
847
	eval "public_$action $*"
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
848
849
	_debuglog ">>> DONE public_$action $CM_fqdn $*"

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
850
851
852
853
854
855
856
else
	self=$( basename $0 )
	cat <<EOF

HELP

The basic syntax is
857
$self [--trace] ACTION [FQDN] [ALIAS_1 [.. ALIAS_N]]
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
858

859
The ACTIONs for SINGLE certificate handlings are:
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
860

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
861
862
        add FQDN [.. FQDN-N] 
                create new certificate
863
864
865
                The first FQDN is a hostname to generate the certificate for. 
                Following multiple hostnames will be used as DNS aliases in the 
                same certificate.
866
                It updates files in ${CM_diracme}
867

868
869
870
871
872
        ensure FQDN [.. FQDN-N] 
                It ensures that a certificate with given aliases exists and is up to date.
                This param is for simple usage in automation tools like Ansible or Puppet.
                It is required to add all aliases as parameters what is unhandy for
                direct usage on cli.
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
873

874
875
876
877
878
                If the cert does not exist it will be created (see "add").
                If fqdn and aliases are the same like in the certificate it performs a renew.
                If fqdn and aliases differ:
                - the current certificate will be rejected + deleted (see "delete")
                - a new certificate will be added ()
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
879

880
        delete FQDN
881
                delete all files of a given certificate
882
883
884

        renew FQDN
                renew (an already added) certificate
885
                and update files in ${CM_diracme}
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
886

887
        show FQDN
888
                show place of certificate data and show basic certificate data
889
                (issuer, subject, aliases, ending date)
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
890

891
892
893
894
        transfer FQDN
                Transfer cert from acme.sh internal cache to our output dir again.
                It is done during add or renew. With transfer command you can repeat it.

895
ACTIONs for ALL certs
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
896

897
898
        list
                list all certificates including creation and renew date
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
899

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
900
901
902
903
904
905
906
        list-old
                list all certificates older 65 and older 90 days and exit.
				Exitcodes:
				  0 - all certs are up to date.
				  1 - certificates to renew were found
				  2 - outdatedt certificates were found

907
908
909
        renew-all
                renew all certificates (fast mode - without --force)
                and update files in ${CM_diracme}
Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
910
911
912
913
914
915
916
                It is useful for a cronjob.

other ACTIONs

        selftest
                check of health with current setup and requirements.
                This command is helpful for initial setups.
917

918
919
920
921
922
OPTIONS
        --trace (it must be the 1st parameter) 
                the output additionally will be written into a tracelog file 
                below $logdir.

Hahn Axel (hahn)'s avatar
Hahn Axel (hahn) committed
923
924
EOF
fi
925
926

echo
927
_testStaging