aboutsummaryrefslogtreecommitdiff
path: root/net/uacme/files/run.sh
blob: ce82af6b9b318389e60f5148c06367debbbf8e33 (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
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
#!/bin/sh
# Wrapper for uacme to work on openwrt.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# Initial Author: Toke Høiland-Jørgensen <toke@toke.dk>
# Adapted for uacme: Lucian Cristian <lucian.cristian@gmail.com>
# Adapted for custom CA and TLS-ALPN-01: Peter Putzer <openwrt@mundschenk.at>

CHECK_CRON=$1

#check for installed packages, for now, support only one
if [ -e "/usr/lib/acme/acme.sh" ]; then
    ACME=/usr/lib/acme/acme.sh
    APP=acme
elif [ -e "/usr/sbin/uacme" ]; then
    ACME=/usr/sbin/uacme
    HPROGRAM=/usr/share/uacme/uacme.sh
    APP=uacme
else
    echo "Please install ACME or uACME package"
    return 1
fi

export CURL_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt
export NO_TIMESTAMP=1

UHTTPD_LISTEN_HTTP=
PRODUCTION_STATE_DIR='/etc/acme'
STAGING_STATE_DIR='/etc/acme/staging'

ACCOUNT_EMAIL=
DEBUG=0
NGINX_WEBSERVER=0
UPDATE_NGINX=0
UPDATE_UHTTPD=0
UPDATE_HAPROXY=0
FW_RULE=
USER_CLEANUP=
ACME_URL=
ACME_STAGING_URL=

. /lib/functions.sh

check_cron()
{
    [ -f "/etc/crontabs/root" ] && grep -q '/etc/init.d/acme' /etc/crontabs/root && return
    echo "0 0 * * * /etc/init.d/acme start" >> /etc/crontabs/root
    /etc/init.d/cron start
}

log()
{
    logger -t $APP -s -p daemon.info "$@"
}

err()
{
    logger -t $APP -s -p daemon.err "$@"
}

debug()
{
    [ "$DEBUG" -eq "1" ] && logger -t $APP -s -p daemon.debug "$@"
}

get_listeners() {
    local proto rq sq listen remote state program
    netstat -nptl 2>/dev/null | while read proto listen program; do
        case "$proto#$listen#$program" in
            tcp#*:80#[0-9]*/*) echo -n "${program%% *} " ;;
        esac
    done
}

pre_checks()
{
    main_domain="$1"

    log "Running pre checks for $main_domain."

    listeners="$(get_listeners)"

    debug "port80 listens: $listeners"

    for listener in $(get_listeners); do
	pid="${listener%/*}"
	cmd="${listener#*/}"

	case "$cmd" in
	    uhttpd)
		debug "Found uhttpd listening on port 80"
		if [ "$APP" = "acme" ]; then
		    UHTTPD_LISTEN_HTTP=$(uci get uhttpd.main.listen_http)
		    if [ -z "$UHTTPD_LISTEN_HTTP" ]; then
			err "$main_domain: Unable to find uhttpd listen config."
			err "Manually disable uhttpd or set webroot to continue."
			return 1
		    fi
		    uci set uhttpd.main.listen_http=''
		    uci commit uhttpd || return 1
		    if ! /etc/init.d/uhttpd reload ; then
			uci set uhttpd.main.listen_http="$UHTTPD_LISTEN_HTTP"
			uci commit uhttpd
			return 1
		    fi
		fi
	    ;;
	    nginx*)
		debug "Found nginx listening on port 80"
		NGINX_WEBSERVER=1
		if [ "$APP" = "acme" ]; then
		    local tries=0
		    while grep -sq "$cmd" "/proc/$pid/cmdline" && kill -0 "$pid"; do
		    /etc/init.d/nginx stop
			if [ $tries -gt 10 ]; then
			    debug "Can't stop nginx. Terminating script."
			    return 1
			fi
		    debug "Waiting for nginx to stop..."
		    tries=$((tries + 1))
		    sleep 1
		    done
		fi
            ;;
	    "")
		err "Nothing listening on port 80."
		err "Standalone mode not supported, setup uhttpd or nginx"
		return 1
            ;;
            *)
		err "$main_domain: unsupported (apache/haproxy?) daemon is listening on port 80."
		err "if webroot is set on your current webserver comment line 132 (return 1) from this script."
		return 1
            ;;
	esac
    done

    FW_RULE=$(uci add firewall rule) || return 1
    uci set firewall."$FW_RULE".name='uacme: temporarily allow incoming http'
    uci set firewall."$FW_RULE".enabled='1'
    uci set firewall."$FW_RULE".target='ACCEPT'
    uci set firewall."$FW_RULE".src='wan'
    uci set firewall."$FW_RULE".proto='tcp'
    uci set firewall."$FW_RULE".dest_port='80'
    uci commit firewall
    /etc/init.d/firewall reload

    debug "added firewall rule: $FW_RULE"
    return 0
}

post_checks()
{
    log "Running post checks (cleanup)."
    # $FW_RULE contains the string to identify firewall rule created earlier
    if [ -n "$FW_RULE" ]; then
	uci delete firewall."$FW_RULE"
	uci commit firewall
	/etc/init.d/firewall reload
    fi

    if [ -e /etc/init.d/uhttpd ] && [ "$UPDATE_UHTTPD" -eq 1 ]; then
	uci commit uhttpd
	/etc/init.d/uhttpd reload
	log "Restarting uhttpd..."
    fi

    if [ -e /etc/init.d/nginx ] && ( [ "$NGINX_WEBSERVER" -eq 1 ] || [ "$UPDATE_NGINX" -eq 1 ]; ); then
	NGINX_WEBSERVER=0
	/etc/init.d/nginx restart
	log "Restarting nginx..."
    fi

    if [ -e /etc/init.d/haproxy ] && [ "$UPDATE_HAPROXY" -eq 1 ]; then
	/etc/init.d/haproxy restart
	log "Restarting haproxy..."
    fi

    if [ -n "$USER_CLEANUP" ] && [ -f "$USER_CLEANUP" ]; then
	log "Running user-provided cleanup script from $USER_CLEANUP."
	"$USER_CLEANUP" || return 1
    fi
}

err_out()
{
    post_checks
    exit 1
}

int_out()
{
    post_checks
    trap - INT
    kill -INT $$
}

is_staging()
{
    local main_domain="$1"

    grep -q "acme-staging" "$STATE_DIR/$main_domain/${main_domain}.conf"
    return $?
}

issue_cert()
{
    local section="$1"
    local acme_args=
    local debug=
    local enabled
    local use_staging
    local update_uhttpd
    local update_nginx
    local update_haproxy
    local keylength
    local domains
    local main_domain
    local failed_dir
    local webroot
    local dns
    local tls
    local user_setup
    local user_cleanup
    local ret
    local staging=
    local HOOK=

    # reload uci values, as the value of use_staging may have changed
    config_load acme
    config_get_bool enabled "$section" enabled 0
    config_get_bool use_staging "$section" use_staging
    config_get_bool update_uhttpd "$section" update_uhttpd
    config_get_bool update_nginx "$section" update_nginx
    config_get_bool update_haproxy "$section" update_haproxy
    config_get domains "$section" domains
    config_get keylength "$section" keylength
    config_get webroot "$section" webroot
    config_get dns "$section" dns
    config_get tls "$section" tls
    config_get user_setup "$section" user_setup
    config_get user_cleanup "$section" user_cleanup

    UPDATE_NGINX=$update_nginx
    UPDATE_UHTTPD=$update_uhttpd
    UPDATE_HAPROXY=$update_haproxy
    USER_CLEANUP=$user_cleanup

    [ "$enabled" -eq "1" ] || return 0

    if [ "$APP" = "uacme" ]; then
	[ "$DEBUG" -eq "1" ] && debug="--verbose --verbose"
	[ "$tls" -eq "1" ] && HPROGRAM=/usr/share/uacme/ualpn.sh
    elif [ "$APP" = "acme" ]; then
	[ "$DEBUG" -eq "1" ] && acme_args="$acme_args --debug"
    fi
    if [ "$use_staging" -eq "1" ]; then
	STATE_DIR="$STAGING_STATE_DIR";

	# Check if we should use a custom stagin URL
        if [ "$APP" = "uacme" -a -n "$ACME_STAGING_URL" ]; then
        	ACME="$ACME --acme-url $ACME_STAGING_URL"
	else
		staging="--staging";
	fi
    else
	STATE_DIR="$PRODUCTION_STATE_DIR";
	staging="";

	if [ "$APP" = "uacme" -a -n "$ACME_URL" ]; then
		ACME="$ACME --acme-url $ACME_URL"
	fi
    fi

    set -- $domains
    main_domain=$1

    if [ -n "$user_setup" ] && [ -f "$user_setup" ]; then
	log "Running user-provided setup script from $user_setup."
	"$user_setup" "$main_domain" || return 2
    else
	[ -n "$webroot" ] || [ -n "$dns" ] || [ -n "$tls" ] || pre_checks "$main_domain" || return 2
    fi

    log "Running $APP for $main_domain"

    if [ "$APP" = "uacme" ]; then
	if [ ! -f  "$STATE_DIR/private/key.pem" ]; then
	    log "Create a new ACME account with email $ACCOUNT_EMAIL use staging=$use_staging"
	    $ACME $debug --confdir "$STATE_DIR" $staging --yes new $ACCOUNT_EMAIL
	fi

	if [ -f "$STATE_DIR/$main_domain/cert.pem" ]; then
	    log "Found previous cert config, use staging=$use_staging. Issuing renew."
	    export CHALLENGE_PATH="$webroot"
	    $ACME $debug --confdir "$STATE_DIR" $staging --never-create issue $domains --hook=$HPROGRAM; ret=$?
	    post_checks
	    return $ret
	fi
    fi
    if [ "$APP" = "acme" ]; then
	handle_credentials() {
	    local credential="$1"
	    eval export "$credential"
	}
	config_list_foreach "$section" credentials handle_credentials

	if [ -e "$STATE_DIR/$main_domain" ]; then
	    if [ "$use_staging" -eq "0" ] && is_staging "$main_domain"; then
		log "Found previous cert issued using staging server. Moving it out of the way."
		mv "$STATE_DIR/$main_domain" "$STATE_DIR/$main_domain.staging"
	    else
		log "Found previous cert config. Issuing renew."
		$ACME --home "$STATE_DIR" --renew -d "$main_domain" "$acme_args"; ret=$?
		post_checks
		return $ret
	    fi
	fi
    fi

    acme_args="$acme_args --bits $keylength"
    acme_args="$acme_args $(for d in $domains; do echo -n " $d "; done)"
    if [ "$APP" = "acme" ]; then
	[ -n "$ACCOUNT_EMAIL" ] && acme_args="$acme_args --accountemail $ACCOUNT_EMAIL"
	[ "$use_staging" -eq "1" ] && acme_args="$acme_args --staging"
    fi
    if [ -n "$dns" ]; then
#TO-DO
	if [ "$APP" = "acme" ]; then
	    log "Using dns mode"
	    acme_args="$acme_args --dns $dns"
	else
	    log "Using dns mode, dns-01 is not wrapped yet"
	    return 2
#	    uacme_args="$uacme_args --dns $dns"
	fi
    elif [ -n "$tls" ]; then
	if [ "$APP" = "uacme" ]; then
            log "Using TLS mode"
	else
            log "TLS not supported by $APP"
            return 2
	fi
    elif [ -z "$webroot" ]; then
	if [ "$APP" = "acme" ]; then
	    log "Using standalone mode"
	    acme_args="$acme_args --standalone --listen-v6"
	else
	    log "Standalone not supported by $APP"
	    return 2
	fi
    else
	if [ ! -d "$webroot" ]; then
	    err "$main_domain: Webroot dir '$webroot' does not exist!"
	    post_checks
	    return 2
	fi
	log "Using webroot dir: $webroot"
	if [ "$APP" = "uacme" ]; then
	    export CHALLENGE_PATH="$webroot"
	else
	    acme_args="$acme_args --webroot $webroot"
	fi
    fi

    if [ "$APP" = "uacme" ]; then
	workdir="--confdir"
	HOOK="--hook=$HPROGRAM"
    else
	workdir="--home"
    fi

    $ACME $debug $workdir "$STATE_DIR" $staging issue $acme_args $HOOK; ret=$?
    if [ "$ret" -ne 0 ]; then
	failed_dir="$STATE_DIR/${main_domain}.failed-$(date +%s)"
	err "Issuing cert for $main_domain failed. Moving state to $failed_dir"
	[ -d "$STATE_DIR/$main_domain" ] && mv "$STATE_DIR/$main_domain" "$failed_dir"
	[ -d "$STATE_DIR/private/$main_domain" ] && mv "$STATE_DIR/private/$main_domain" "$failed_dir"
	post_checks
	return $ret
    fi

    if [ -e /etc/init.d/uhttpd ] && [ "$update_uhttpd" -eq "1" ]; then
	if [ "$APP" = "uacme" ]; then
	    uci set uhttpd.main.key="$STATE_DIR/private/${main_domain}/key.pem"
	    uci set uhttpd.main.cert="$STATE_DIR/${main_domain}/cert.pem"
	else
	    uci set uhttpd.main.key="$STATE_DIR/${main_domain}/${main_domain}.key"
	    uci set uhttpd.main.cert="$STATE_DIR/${main_domain}/fullchain.cer"
	fi
	# commit and reload is in post_checks
    fi

    local nginx_updated
    nginx_updated=0
    if command -v nginx-util 2>/dev/null && [ "$update_nginx" -eq "1" ]; then
	nginx_updated=1
	for domain in $domains; do
	    if [ "$APP" = "uacme" ]; then
		nginx-util add_ssl "${domain}" uacme "$STATE_DIR/${main_domain}/cert.pem" \
		    "$STATE_DIR/private/${main_domain}/key.pem" || nginx_updated=0
	    else
		nginx-util add_ssl "${domain}" acme "$STATE_DIR/${main_domain}/fullchain.cer" \
		    "$STATE_DIR/${main_domain}/${main_domain}.key" || nginx_updated=0
	    fi
	done
	# reload is in post_checks
    fi

    if [ "$nginx_updated" -eq "0" ] && [ -w /etc/nginx/nginx.conf ] && [ "$update_nginx" -eq "1" ]; then
	if [ "$APP" = "uacme" ]; then
	    sed -i "s#ssl_certificate\ .*#ssl_certificate $STATE_DIR/${main_domain}/cert.pem;#g" /etc/nginx/nginx.conf
	    sed -i "s#ssl_certificate_key\ .*#ssl_certificate_key $STATE_DIR/private/${main_domain}/key.pem;#g" /etc/nginx/nginx.conf
	else
	    sed -i "s#ssl_certificate\ .*#ssl_certificate $STATE_DIR/${main_domain}/fullchain.cer;#g" /etc/nginx/nginx.conf
	    sed -i "s#ssl_certificate_key\ .*#ssl_certificate_key $STATE_DIR/${main_domain}/${main_domain}.key;#g" /etc/nginx/nginx.conf
	fi
	# commit and reload is in post_checks
    fi

    if [ -e /etc/init.d/haproxy ] && [ "$update_haproxy" -eq 1 ]; then
	if [ "$APP" = "uacme" ]; then
	    cat $STATE_DIR/${main_domain}/cert.pem $STATE_DIR/private/${main_domain}/key.pem > $STATE_DIR/${main_domain}/full_haproxy.pem
	else
	    cat $STATE_DIR/${main_domain}/fullchain.cer $STATE_DIR/${main_domain}/${main_domain}.key > $STATE_DIR/${main_domain}/full_haproxy.pem
	fi
    fi

    post_checks
}

issue_cert_with_retries() {
	local section="$1"
	local use_staging
	local retries
	local use_auto_staging
	local infinite_retries
	config_get_bool use_staging "$section" use_staging
	config_get_bool use_auto_staging "$section" use_auto_staging
	config_get_bool enabled "$section" enabled
	config_get retries "$section" retries

	[ -z "$retries" ] && retries=1
	[ -z "$use_auto_staging" ] && use_auto_staging=0
	[ "$retries" -eq "0" ] && infinite_retries=1
	[ "$enabled" -eq "1" ] || return 0

	while true; do
		issue_cert "$1"; ret=$?

		if [ "$ret" -eq "2" ]; then
			# An error occurred while retrieving the certificate.
			retries="$((retries-1))"

			if [ "$use_auto_staging" -eq "1" ] && [ "$use_staging" -eq "0" ]; then
				log "Production certificate could not be obtained. Switching to staging server."
				use_staging=1
				uci set "acme.$1.use_staging=1"
				uci commit acme
			fi

			if [ -z "$infinite_retries" ] && [ "$retries" -lt "1" ]; then
				log "An error occurred while retrieving the certificate. Retries exceeded."
				return "$ret"
			fi

			if [ "$use_staging" -eq "1" ]; then
				# The "Failed Validations" limit of LetsEncrypt is 60 per hour. This
				# means one failure every minute. Here we wait 2 minutes to be within
				# limits for sure.
				sleeptime=120
			else
				# There is a "Failed Validation" limit of LetsEncrypt is 5 failures per
				# account, per hostname, per hour. This means one failure every 12
				# minutes. Here we wait 25 minutes to be within limits for sure.
				sleeptime=1500
			fi

			log "An error occurred while retrieving the certificate. Retrying in $sleeptime seconds."
			sleep "$sleeptime"
			continue
		else
			if [ "$use_auto_staging" -eq "1" ]; then
				if [ "$use_staging" -eq "0" ]; then
					log "Production certificate obtained. Exiting."
				else
					log "Staging certificate obtained. Continuing with production server."
					use_staging=0
					uci set "acme.$1.use_staging=0"
					uci commit acme
					continue
				fi
			fi

			return "$ret"
		fi
	done
}

load_vars()
{
    local section="$1"

    PRODUCTION_STATE_DIR=$(config_get "$section" state_dir)
    STAGING_STATE_DIR=$PRODUCTION_STATE_DIR/staging
    ACCOUNT_EMAIL=$(config_get "$section" account_email)
    DEBUG=$(config_get "$section" debug)
    ACME_URL=$(config_get "$section" acme_url)
    ACME_STAGING_URL=$(config_get "$section" acme_staging_url)
}

if [ -z "$INCLUDE_ONLY" ]; then
    check_cron
    [ -n "$CHECK_CRON" ] && exit 0
    [ -e "/var/run/acme_boot" ] && rm -f "/var/run/acme_boot" && exit 0
fi

config_load acme
config_foreach load_vars acme

if [ -z "$PRODUCTION_STATE_DIR" ] || [ -z "$ACCOUNT_EMAIL" ]; then
    err "state_dir and account_email must be set"
    exit 1
fi

[ -d "$PRODUCTION_STATE_DIR" ] || mkdir -p "$PRODUCTION_STATE_DIR"
[ -d "$STAGING_STATE_DIR" ] || mkdir -p "$STAGING_STATE_DIR"

trap err_out HUP TERM
trap int_out INT

if [ -z "$INCLUDE_ONLY" ]; then
    config_foreach issue_cert_with_retries cert

    exit 0
fi