-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcertbot.sh
executable file
·2669 lines (2175 loc) · 80.3 KB
/
certbot.sh
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# Apache License 2.0
#
# Copyright (c) 2020 Serhey Popovych <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This program name
this_prog='certbot.sh'
# User to run certbot
_runas='letsencrypt'
runas="${runas:-${_runas}}"
# Group whose members able to $runas $this_prog
_certmgr='certbot'
certmgr="${certmgr:-${_certmgr}}"
# Where to install this program and symlink wrappers
install_to="/usr/local/lib/$this_prog"
symlink_dirs='/usr/local/bin /usr/local/sbin'
################################################################################
# Usage: installer ...
installer()
{
# Requires: install(1), mktemp(1), ls(1), chmod(1), chown(1), mv(1), rm(1),
# ln(1), cat(1), sed(1), cmp(1),
# useradd(8), usermod(8), groupadd(8), id(1),
# certbot, lighttpd(8),
# systemd(timers) or crond(8), logrotate(8), killall(1) (psmisc)
#
# Optional: named(8) - to configure subdomain for TXT records managed by
# certbot dns-rfc2136 plugin via dynamic updates
# patch(1) - to apply dns-rfc2136 plugin CNAME/DNAME fix from
# ~${runas}/extra/bind.
#
# Config: $this_prog, $runas, $certmgr, $install_to, $symlink_dirs
# Runtime: $this, $this_dir, $prog_name
# Usage: normalize_path() <path>
normalize_path()
{
local func="${FUNCNAME:-normalize_path}"
local path="${1:?missing 1st arg to ${func}() (<path>)}"
local file=''
if [ ! -d "${path}" ]; then
file="${path##*/}"
[ -n "$file" ] || return
path="${path%/*}/"
[ -d "$path" ] || return
fi
cd "${path}" &&
path="${PWD%/}/${file}" &&
cd - >/dev/null || return
echo "${path}"
}
# Usage: relative_path <src> <dst>
relative_path()
{
local func="${FUNCNAME:-relative_path}"
local rp_src="${1:?missing 1st arg to ${func}() (<src>)}"
local rp_dst="${2:?missing 2d arg to ${func}() (<dst>)}"
# add last component from src if dst ends with '/'
[ -n "${rp_dst##*/}" ] || rp_dst="${rp_dst}${rp_src##*/}"
# normalize pathes first
rp_src="$(normalize_path "${rp_src}")" || return
rp_dst="$(normalize_path "${rp_dst}")" || return
# strip leading and add trailing '/'
rp_src="${rp_src#/}/"
rp_dst="${rp_dst#/}/"
while :; do
[ "${rp_src%%/*}" = "${rp_dst%%/*}" ] || break
rp_src="${rp_src#*/}" && [ -n "${rp_src}" ] || return
rp_dst="${rp_dst#*/}" && [ -n "${rp_dst}" ] || return
done
# strip trailing '/'
rp_dst="${rp_dst%/}"
rp_src="${rp_src%/}"
# add leading '/' for dst only: for src we will add with sed(1) ../
rp_dst="/${rp_dst}"
# add leading '/' to dst, replace (/[^/])+ with ../
rp_dst="$(echo "${rp_dst%/*}" | \
sed -e 's|\(/[^/]\+\)|../|g')${rp_src}" || \
return
echo "${rp_dst}"
}
# Usage: rights_human2octal <rights>
rights_human2octal()
{
local func="${FUNCNAME:-rights_human2octal}"
# rwxr-xr-x (755), rwsrwSrwT (7766)
local rights="${1:?missing 1st arg to ${func}() <rights>}"
[ ${#rights} -eq 9 ] || return
local val=0
local g v s c C r
# groups: 3 2 1 0
# bits: sgtrwxrwxrwx
for g in 2 1 0; do
v=0
s=0
if [ $g -ge 1 ]; then
c='s' && C='S'
else
c='t' && C='T'
fi
r="${rights#[r-][w-][xsStT-]}"
r="${rights%$r}"
# [r-]
case "$r" in
r??) v=$((4 + v)) ;;
-??) ;;
*) return 1 ;;
esac
# [w-]
case "$r" in
?w?) v=$((2 + v)) ;;
?-?) ;;
*) return 1 ;;
esac
# [xsStT-]
case "$r" in
??x) v=$((1 + v)) ;;
??$c) v=$((1 + v)) && s=$((1 << g)) ;;
??$C) s=$((1 << g)) ;;
??-) ;;
*) return 1 ;;
esac
val=$((val | v << (3 * g) | s << (3 * 3)))
rights="${rights#$r}"
done
printf '%04o\n' "$val"
}
# Usage: file_rights_human <file>
file_rights_human()
{
local func="${FUNCNAME:-file_rights_human}"
local file="${1:?missing 1st arg to ${func}() <file>}"
[ -e "$file" ] || return
set -- $(ls -l "$file") || return
local rights="$1"
rights="${rights#?}"
[ ${#rights} -eq 9 ] || rights="${rights%?}"
case "$rights" in
[r-][w-][xsS-][r-][w-][xsS-][r-][w-][xtT-]) ;;
*) return 1 ;;
esac
echo "$rights"
}
# Usage: file_rights_octal <file>
file_rights_octal()
{
local func="${FUNCNAME:-file_rights_octal}"
local file="${1:?missing 1st arg to ${func}() <file>}"
local rights
rights="$(file_rights_human "$file")" || return
rights_human2octal "$rights"
}
# Usage: file_owner_human <file>
file_owner_human()
{
local func="${FUNCNAME:-file_owner_human}"
local file="${1:?missing 1st arg to ${func}() <file>}"
[ -e "$file" ] || return
set -- $(ls -l "$file") || return
[ -n "$3" -a -n "$4" ] || return
echo "$3:$4"
}
# Usage: file_owner_octal <file>
file_owner_octal()
{
local func="${FUNCNAME:-file_owner_octal}"
local file="${1:?missing 1st arg to ${func}() <file>}"
local owner uid gid
owner="$(file_owner_human "$file")" || return
uid="$(id -u "${owner%:*}")" || return
gid="$(id -g "${owner#*:}")" || return
echo "$uid:$gid"
}
# Usage: new <target> [<owner>] [<group>] [<mode>]
new()
{
local func="${FUNCNAME:-new}"
local target="${1:?missing 1st arg to ${func}()}"
local owner="${2:-$runas}"
local group="${3:-root}"
local mode="${4-}"
if [ -e "$target" ]; then
# Directory or non-directory?
if [ -n "${target%%*/}" ]; then
[ -f "$target" ] || return
else
[ -d "$target" ] || return
fi
# Update ownership
chown "$owner:$group" "$target" || return
# Update permissions
[ -z "$mode" ] || chmod "$mode" "$target" || return
else
# Catch recursive call, if any
[ -z "${in_new-}" ] || return
local in_new=1
# There might be broken symlink
rm -f "$target" ||:
# Directory or regular file?
if [ -n "${target%%*/}" ]; then
:>"$target" && new "$@" || return
else
install -d ${mode:+-m $mode} \
-o "$owner" -g "$group" "$target" || return
fi
fi
}
# Usage: put <out>
put()
{
local func="${FUNCNAME:-put}"
local out="${1:?missing 1st arg to ${func}() (<out>)}"
local t m o rc=0
t="$(mktemp "$out.XXXXXXXX")" || return
if cat >"$t"; then
if cmp -s "$t" "$out"; then
:
else
if [ -e "$out" ]; then
m="$(file_rights_octal "$out")" &&
chmod "$m" "$t" || rc=$?
o="$(file_owner_human "$out")" &&
chown "$o" "$t" || rc=$?
fi
while [ $rc -eq 0 ]; do
if [ -L "$out" ] || [ -e "$out" -a ! -f "$out" ]; then
rm -f "$out" ||:
fi
if [ -e "$out" ]; then
[ -z "${put__skip_existing-}" ] || break
out="$out.certbotsh-new"
fi
mv -f "$t" "$out" || rc=$?
break
done
fi
else
rc=$?
fi
[ ! -e "$t" ] || rm -f "$t" || rc=$((rc + $?))
return $rc
}
# Usage: server_http_conf [<hostname>] [<domain>]
server_http_conf()
{
local d="${2:-example.com}"
local h="${1:-acme-le.gw.api.$d}"
local log_root='/var/log/lighttpd'
local server_root='/var/www'
local conf_dir='/etc/lighttpd'
local lighttpd_group='www-data'
if ! id -g "$lighttpd_group" >/dev/null 2>&1; then
lighttpd_group='lighttpd'
if ! id -g "$lighttpd_group" >/dev/null 2>&1; then
groupadd \
-r -f \
"$lighttpd_group" \
#
fi
fi # lighttpd_group
local lighttpd_user='www-data'
if ! id -u "$lighttpd_user" >/dev/null 2>&1; then
lighttpd_user='lighttpd'
if ! id -u "$lighttpd_user" >/dev/null 2>&1; then
useradd \
-r \
-g "$lighttpd_group" \
-c 'lighttpd web server' \
-d "$server_root" \
-s '/bin/false' \
"$lighttpd_user" \
#
fi
fi # lighttpd_user
local s t
t="$conf_dir/" && new "$t" 'root' 'root'
t="${t}lighttpd.conf"
if [ -f "$t" ]; then
s="$t.certbotsh-orig"
[ -f "$s" ] || mv -f "$t" "$s"
fi
put "$t" <<EOF
## Requires lighttpd 1.4.54+
##### Load required server modules #####
server.modules += (
"mod_accesslog",
"mod_openssl",
"mod_access",
# "mod_auth",
# "mod_authn_file",
"mod_evasive",
"mod_setenv",
"mod_userdir",
"mod_redirect",
"mod_rewrite",
)
##### Variable definition which will make configuration easier #####
# Common variables
var.log_root = "$log_root"
var.server_root = "$server_root"
var.state_dir = "/var/run"
var.conf_dir = "$conf_dir"
# Base directory with authentication data
var.auth_dir = conf_dir + "/auth"
# Base directory with certs and keys
var.pki_dir = conf_dir + "/pki"
# Base directory for all vhosts configuration
var.vhosts_d = conf_dir + "/vhosts.d"
##### General server settings #####
# Suppress lighty version from "Server" field in the http headers.
server.tag = "lighttpd"
# Perform initial configuration steps (e.g. open socket
# on privileged port 80, write pid file, change process
# limit on file descriptions, etc.) and drop privileges.
server.username = "$lighttpd_user"
server.groupname = "$lighttpd_group"
# Error logging.
server.errorlog = log_root + "/error.log"
##### Network settings and performance tuning #####
# Explicitly open non-SSL sockets for each address family
server.bind = ""
server.port = 0
# Listen on IPv4 and/or IPv6 socket(s).
\$SERVER["socket"] == "0.0.0.0:80" { }
\$SERVER["socket"] == "[::]:80" { }
# Use high-performance file descriptor event pooling on Linux.
server.event-handler = "linux-sysepoll"
# Use sendfile(2) as backend for sending files.
server.network-backend = "sendfile"
# Increase limit on file descriptors.
server.max-fds = 2048
# Maximum number of connections supported by the server (max-fds / 3).
server.max-connections = 640
# Cache stat(2) syscalls.
server.stat-cache-engine = "simple"
# Tune up socket IO timeouts.
server.max-read-idle = 30
server.max-write-idle = 180
# How many seconds to keep a keep-alive connection open, until we consider it idle.
server.max-keep-alive-idle = 5
# How many keep-alive requests until closing the connection.
server.max-keep-alive-requests = 16
##### Filesystem configurations #####
# Set document root, upload directory etc.
server.document-root = server_root + "/empty"
server.upload-dirs = ( "/var/tmp" )
## Store process id in this file.
#server.pid-file = state_dir + "/lighttpd.pid"
# Do not follow symlinks by default.
server.follow-symlink = "disable"
# Sane index file names by default: each vhost will configure it's own.
index-file.names = ( "index.html" )
# Deny access the file-extensions.
url.access-deny = ( "~", ".bak", ".inc" )
# Directory listing configuration.
dir-listing.activate = "disable"
# mimetype mapping.
mimetype.assign += (
".html" => "text/html",
"" => "application/octet-stream"
)
##### Access logging options #####
# Access log configuration.
accesslog.filename = log_root + "/access.log"
##### SSL configuration #####
# Enable globally
ssl.engine = "enable"
ssl.cipher-list = "TLSv1.2:!aNULL:!eNULL:!LOW:!MEDIUM:!EXP:!kRSA:!AES256"
# It is expected that global certificate is a wildcard
# including second and above subdomains as subjectAltName (SAN)
ssl.pemfile = pki_dir + "/wildcard/" + "cert.pem"
ssl.privkey = pki_dir + "/wildcard/" + "privkey.pem" # 1.4.53+
ssl.ca-file = pki_dir + "/wildcard/" + "chain.pem"
#ssl.dh-file = pki_dir + "/dh2048.pem"
# Inherit global settings (not only SSL) in 1.4.46+
# https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_SSL
\$SERVER["socket"] == "0.0.0.0:443" { ssl.engine = "enable" }
\$SERVER["socket"] == "[::]:443" { ssl.engine = "enable" }
##### Virtual hosts #####
# Include vhosts configuration.
include vhosts_d + "/*/conf"
EOF
new "$t" 'root' 'root' 0644
# $conf_dir/auth
new "$conf_dir/auth/" 'root' 'root'
# $conf_dir/pki
t="$conf_dir/pki/" && new "$t" 'root' 'root'
cd "$t" &&
ln -sf "../../letsencrypt/live/$h" &&
ln -sf "../../letsencrypt/live/$d" &&
ln -sf "$d" 'wildcard' &&
cd - >/dev/null
# $conf_dir/vhosts.d/$h
s="$conf_dir/vhosts.d/$h"
new "$s/auth/" 'root' 'root'
new "$s/conf.d/" 'root' 'root'
# $conf_dir/vhosts.d/$h/pki
ln -sf "../../pki/$h" "$s/pki"
# $conf_dir/vhosts.d/$h/users.d
t="$s/users.d/" && new "$t" 'root' 'root'
# $conf_dir/vhosts.d/$h/xbin/users-conf.sh
t="$s/xbin/" && new "$t" 'root' 'root'
# $conf_dir/vhosts.d/$h/conf
t="$s/conf" && put "$t" <<EOF
\$HTTP["host"] =~ "^$(echo "$h" | sed -e 's/\./\\./g')(:|\$)" {
var.server_name = "$h"
## common filesystem paths
var.vhosts_d = vhosts_d + "/" + server_name
var.auth_dir = vhosts_d + "/auth"
var.pki_dir = vhosts_d + "/pki"
var.xbin_dir = vhosts_d + "/xbin"
var.log_root = log_root + "/" + server_name
## userdir
var.userdir_include_users = (
"${runas}"
)
var.userdir_path = "${htdocsdir##*/}"
# Common server configuration
server.name = server_name
# Must be empty, read-only directory
server.document-root = server_root + "/empty"
# Forbid all http methods except GET
\$HTTP["request-method"] !~ "^GET\$" {
url.access-deny = ( "" )
}
# User home subdirectory
userdir.path = userdir_path
userdir.include-user = userdir_include_users
# Access logging
accesslog.filename = log_root + "/access.log"
\$HTTP["scheme"] == "http" {
# Tune up socket IO timeouts
server.max-read-idle = 30
server.max-write-idle = 60
# Disable keep-alive functionality
server.max-keep-alive-requests = 0
url.redirect-code = 301
# This requires 1.4.50+ as we do not have access to %n from \$HTTP["host"] here
url.redirect = ( "" => "https://\${url.authority}\${url.path}\${qsa}" )
}
\$HTTP["scheme"] == "https" {
# SSL
ssl.pemfile = pki_dir + "/cert.pem"
ssl.privkey = pki_dir + "/privkey.pem" # 1.4.53+
ssl.ca-file = pki_dir + "/chain.pem"
# HSTS
setenv.add-response-header += (
"Strict-Transport-Security" => "max-age=31536000; includeSubdomains"
)
# Follow symlinks
server.follow-symlink = "enable"
# Make PKCS#12 accessible only from remote IPs of host they issued to
$HTTP["remoteip"] =~ ".+" {
url.rewrite-once = (
"^/(~[^/]+)((/[^/]+)*)/(([^/]+)\.p12)$" => "/$1/$5/%0$2/$4",
"" => "/"
)
}
# Per IP connection limit
evasive.max-conns-per-ip = 10
evasive.silent = "disable"
# # Authentication
# auth.backend = "htdigest"
# auth.backend.htdigest.userfile = auth_dir + "/users.htdigest"
#
# auth.require = ( "" =>
# (
# "method" => "digest",
# "realm" => "Restricted area",
# "require" => "user=${runas}"
# )
# )
}
}
EOF
new "$t" 'root' 'root' 0644
# $server_root/empty
t="$server_root/empty/" && new "$t" 'root' 'root' 0755
t="${t}index.html" && put "$t" <<'_EOF'
_EOF
new "$t" 'root' 'root' 0644
# $log_root/$h
t="$log_root/" && new "$t" "$lighttpd_user" "$lighttpd_group" 0750
s="$log_root/$h/" && new "$s" "$lighttpd_user" "$lighttpd_group" 0750
# /etc/logrotate.d/lighttpd.$h
t='/etc/logrotate.d/' && new "$t" 'root' 'root'
t="${t}lighttpd.$h" && put "$t" <<EOF
${s}*log {
missingok
notifempty
sharedscripts
su ${lighttpd_user} ${lighttpd_group}
postrotate
/usr/bin/killall -HUP lighttpd >/dev/null 2>&1 || :
endscript
}
EOF
new "$t" 'root' 'root' 0644
} # server_http_conf
# Usage: server_cron_conf ...
server_cron_conf()
{
local s t
# Provide crontab entries for certificate renewal that bail out
# on systemd(1) targets that assumed to use systemd.timer(5) and
# executed on non systemd(1) targets.
t='/etc/cron.d/' && new "$t" 'root' 'root'
t="${t}certbot" && put "$t" <<EOF
# $t: crontab entries for the certbot package
#
# Upstream recommends attempting renewal twice a day
#
# Eventually, this will be an opportunity to validate certificates
# haven't been revoked, etc. Renewal will only occur if expiration
# is within 30 days.
SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
0 */12 * * * ${runas} test \! -d /run/systemd/system && sleep \$((\$$ \% 43200)) && certbot -q renew
EOF
new "$t" 'root' 'root' 0644
# Tweak systemd.service unit to $runas and enable timer
for s in \
'certbot.service' \
'certbot-renew.service' \
#
do
t="/lib/systemd/system/$s"
[ -f "$t" ] || continue
sed -e "/^Type=oneshot\$/aUser=${runas}\\
Group=${runas}" "$t" >"/etc/systemd/system/$s"
t="${s%.service}.timer"
systemctl enable --now "$t"
break
done
} # server_cron_conf
# Usage: server_log_conf ...
server_log_conf()
{
local s t
# Configure logging
s='/var/log/letsencrypt/' && new "$s"
# Config logrotate
t='/etc/logrotate.d/' && new "$t" 'root' 'root'
t="${t}certbot" && put "$t" <<EOF
${s}*.log {
rotate 12
weekly
su ${runas} ${runas}
compress
missingok
}
EOF
new "$t" 'root' 'root' 0644
} # server_log_conf
# Usage: server_extra_conf ...
server_extra_conf()
{
[ -d "$extradir" ] || return
local s t
# bind
s="$extradir/bind/"
t="$s" && new "$t" "$runas" "$runas" 0755
# named.acme-le.zones
t="${s}named._acme-le.zones" && put "$t" <<'_EOF'
zone "_acme-le.example.com" IN {
type master;
file "named._acme-le.example.com";
update-policy {
grant acme-le.gw.api.example.com-key wildcard *._acme-le.example.com. txt;
};
};
_EOF
new "$t" "$runas" "$runas" 0644
# named._acme-le.example.com
t="${s}named._acme-le.example.com" && put "$t" <<'_EOF'
$TTL 21600 ; 6 hours
@ IN SOA ns hostmaster.example.com. (
2020031256 ; serial
21600 ; refresh (6 hours)
3600 ; retry (1 hour)
1209600 ; expire (2 weeks)
3600 ; minimum (1 hour)
)
IN NS ns
IN A 127.0.1.1
ns IN A 127.0.1.1
_EOF
new "$t" "$runas" "$runas" 0644
# README
t="${s}README" && put "$t" <<'_EOF'
This example BIND9 configuration and zone files for Dynamic DNS updates
as per rfc2136 that will be used with certbot dns-rfc2136 plugin.
Steps necessary to configure BIND may vary from distro to distro, however
they can be summarized to following:
1) copy named._acme-le.zones file to /etc/
2) add following directive to
include "/etc/named._acme-le.zones";
to /etc/named.local.zones
3) copy named._acme-le.example.com to /var/named;
make sure user running named(8) service can write to that file
and directory containing it for Dynamic DNS updates support
4) generate TSIG key to control
tsig-keygen >>/etc/named.tsig.key \
-a hmac-sha256 acme-le.gw.api.example.com-key
(make sure /etc/named.tsig.key included from named.conf
or other file included from named.conf)
5) adjust values (espeically serial) in named._acme-le.example.com
and restart named(8) service (e.g. service named restart); check
its status
6) delegate subdomain _acme-le.example.com from example.com;
this can be either done by configuring example.com zone file
or using hosting provider control panel.
For security reasons it is not recommended to run bind service to
perform dns-01 authentications on same host where certbot is running
(i.e. acme-le.gw.api.example.com): in case of any flaws in publicly
available network service that host might be compromised giving access
to certificate management communication channel.
For same reason firewall must be configured on certbot host to restrict
access to other services (e.g. http/ssh server).
Instead dedicated server/container should be provisioned for that purpose.
_EOF
new "$t" "$runas" "$runas" 0644
# certbot
s="$extradir/certbot/"
t="$s" && new "$t" "$runas" "$runas" 0755
# dns-rfc2136 plugin patch (rebased for version 1.0.0 in EPEL7)
local n='dns-rfc2136-cname-and-dname.patch'
t="${s}${n}" && put "$t" <<'_EOF'
From 3774046bd5fc58a6fb29fcfcdefbf66dc4cb517a Mon Sep 17 00:00:00 2001
From: "H. Peter Anvin" <[email protected]>
Date: Thu, 21 Feb 2019 12:36:26 -0800
Subject: [PATCH] dns-rfc2136: find the correct zone/name when CNAME/DNAMEs are
used
Dynamic zones have significant problems with DNSSEC and with redundant
servers (which, of course is highly desirable for DNS.) The obvious
solution to that is to use a CNAME or DNAME record to point the
_acme-challenge to a different zone which can have different NS and
TTL properties. In particular, breaking DNSSEC support breaks exactly
the chain of trust on which ACME depends, and is thus extremely
undesirable.
In order to find the correct base zone and name-in-zone when
CNAME/DNAMEs might be present, search from the top down instead of the
bottom up, and allow non-authoritative answers for anything other than
the final SOA. There is no guarantee that the authentication server is
authoritative for anything but the zone into which the TXT record is
to be placed.
If the authentication server disallows recursion, this code will this
do the right thing as long as the server is authoritative for the
dynamic zone and any zone which contains a CNAME or DNAME record. If
that is not the case, then the server must support recursion for its
dynamic clients; it obviously does not need to offer that service to
the general public. If even this turns out to be unacceptable, then
the solution would be to query the normal nameservers (using the
system resolver), at least if an !AA !RA response is returned. The
dns.resolver module has a zone_for_name() function, but unfortunately
it does not return the name-in-zone, and to me its algorithm appears
to be incorrect (at least for our purposes) in a way that is similar
to the previous dns-rfc2136 code.
This patch changes several levels of the interface to use
dns.name.Name objects instead of strings, and passes dns.rdata.Rdata
objects between _query_soa() and _find_domain(). This turns out to
significantly simplify a fair number of things, but requires a fair
number of changes to the test suite. Clean up the test suite by
implementing a mock resolver with a mapping instead of a simple
sequence of return values, and by precomputing dns.name.Name objects
for (sub)domains and prefixes used.
Signed-off-by: H. Peter Anvin <[email protected]>
---
https://bugzilla.redhat.com/show_bug.cgi?id=1679796
https://github.com/certbot/certbot/pull/7244
diff -urN a/dns_rfc2136.py b/dns_rfc2136.py
--- a/dns_rfc2136.py
+++ b/dns_rfc2136.py
@@ -15,6 +15,7 @@
from certbot import errors
from certbot import interfaces
from certbot.plugins import dns_common
+from collections import defaultdict
logger = logging.getLogger(__name__)
@@ -109,11 +110,9 @@
:raises certbot.errors.PluginError: if an error occurs communicating with the DNS server
"""
- domain = self._find_domain(record_name)
+ logger.debug('Adding TXT record: %s %d "%s"', record_name, record_ttl, record_content)
- n = dns.name.from_text(record_name)
- o = dns.name.from_text(domain)
- rel = n.relativize(o)
+ (rel, domain) = self._find_domain(record_name)
update = dns.update.Update(
domain,
@@ -144,11 +143,7 @@
:raises certbot.errors.PluginError: if an error occurs communicating with the DNS server
"""
- domain = self._find_domain(record_name)
-
- n = dns.name.from_text(record_name)
- o = dns.name.from_text(domain)
- rel = n.relativize(o)
+ (rel, domain) = self._find_domain(record_name)
update = dns.update.Update(
domain,
@@ -174,53 +169,156 @@
Find the closest domain with an SOA record for a given domain name.
:param str record_name: The record name for which to find the closest SOA record.
- :returns: The domain, if found.
- :rtype: str
- :raises certbot.errors.PluginError: if no SOA record can be found.
+ :returns: tuple of (`entry`, `zone`) where
+ `entry` - canonical relative entry into the target zone;
+ `zone` - canonical absolute name of the zone to be modified.
+ :rtype: (`dns.name.Name`, `dns.name.Name`)
+ :raises certbot.errors.PluginError: if the search failed for any reason.
"""
- domain_name_guesses = dns_common.base_domain_name_guesses(record_name)
-
- # Loop through until we find an authoritative SOA record
- for guess in domain_name_guesses:
- if self._query_soa(guess):
- return guess
+ # Note: an absolute dns.name.Name ends in dns.name.root, which
+ # is non-empty. Therefore the first prefix.split(1) splits off
+ # dns.name.root, i.e. example.com. -> (example.com, .), not
+ # example.com. -> (example, com.). dns.name.empty, however,
+ # is an actual empty name, has a truth value of False, and is
+ # an identity element for the append operation; thus
+ # dns.name.root + dns.name.empty == dns.name.root.
+ #
+ # This code relies on these properties.
+
+ domain = dns.name.from_text(record_name)
+ prefix = domain
+ suffix = dns.name.empty
+ found = None
+ domstr = str(domain) # For messages, may have a DNAME/CNAME added
+
+ # The domains already queried and the corresponding results
+ domain_names_searched = dict()
+
+ while prefix:
+ (prefix, next_label) = prefix.split(1)
+ suffix = next_label + suffix
+
+ # Don't re-query if we have already been here (normal
+ # during DNAME/CNAME re-walk)
+ if suffix in domain_names_searched:
+ result = domain_names_searched[suffix]
+ else:
+ result = self._query_soa(suffix)
+ domain_names_searched[suffix] = result
+
+ (auth, rr) = result
+ if rr is None:
+ # Nothing to do, just descend the DNS hierarchy
+ pass
+ elif rr.rdtype == dns.rdatatype.SOA:
+ # We found an SOA, authoritative or not
+ found = (auth, prefix, suffix)
+ else:
+ # We found a DNAME or CNAME. We need to start the walk over
+ # from the common point of departure.
+ target = rr.target
+ if target in domain_names_searched:
+ # DNAME/CNAME loop!
+ raise errors.PluginError('%s %s loops seeking SOA for %s',
+ suffix, repr(rr), domstr)
+
+ # Restart from the root, replacing the current suffix
+ prefix = prefix + target
+ suffix = dns.name.empty
+ found = None
+ domstr = str(domain)+' ('+str(prefix)+')' # For messages
+
+ if not found:
+ raise errors.PluginError('No SOA of any kind found for %s',
+ domstr)
+
+ (auth, prefix, suffix) = found
+ if not auth:
+ raise errors.PluginError('SOA %s for %s not authoritative',
+ suffix, domstr)
+ return (prefix, suffix)
- raise errors.PluginError('Unable to determine base domain for {0} using names: {1}.'
- .format(record_name, domain_name_guesses))
-
- def _query_soa(self, domain_name):
+ def _query_soa(self, domain):
"""
Query a domain name for an authoritative SOA record.
- :param str domain_name: The domain name to query for an SOA record.
- :returns: True if found, False otherwise.
- :rtype: bool
+ :param dns.name.Name domain: The domain name to query for an SOA record.
+ :returns: (`authoritative`, `rdata`) if found
+ autoritative bool if response was authoritative
+ rdata dns.rdata.Rdata or None the returned record
+ :rtype: (`bool`, `dns.rdata.Rdata` or `None`)
:raises certbot.errors.PluginError: if no response is received.
"""
- domain = dns.name.from_text(domain_name)
+ # In order to capture any possible CNAMEs, we have to do the
+ # search upward from the root. On the way, any time we find a
+ # SOA record, save it; the final SOA record captured is the