blob: 5d5da1ed23581ef1c9f3796c98c0a5be0c18d5bf [file] [log] [blame]
Matthias Andreas Benkardb382b102021-01-02 15:32:21 +01001#!/bin/bash
2set -o pipefail
3exec 5>&1
4
5# Do not attempt to write to slave
6if [[ ! -z ${REDIS_SLAVEOF_IP} ]]; then
7 export REDIS_CMDLINE="redis-cli -h ${REDIS_SLAVEOF_IP} -p ${REDIS_SLAVEOF_PORT}"
8else
9 export REDIS_CMDLINE="redis-cli -h redis -p 6379"
10fi
11
12until [[ $(${REDIS_CMDLINE} PING) == "PONG" ]]; do
13 echo "Waiting for Redis..."
14 sleep 2
15done
16
17source /srv/functions.sh
18# Thanks to https://github.com/cvmiller -> https://github.com/cvmiller/expand6
19source /srv/expand6.sh
20
21# Skipping IP check when we like to live dangerously
22if [[ "${SKIP_IP_CHECK}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
23 SKIP_IP_CHECK=y
24fi
25
26# Skipping HTTP check when we like to live dangerously
27if [[ "${SKIP_HTTP_VERIFICATION}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
28 SKIP_HTTP_VERIFICATION=y
29fi
30
31# Request certificate for MAILCOW_HOSTNAME only
32if [[ "${ONLY_MAILCOW_HOSTNAME}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
33 ONLY_MAILCOW_HOSTNAME=y
34fi
35
36# Request individual certificate for every domain
37if [[ "${ENABLE_SSL_SNI}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
38 ENABLE_SSL_SNI=y
39fi
40
41if [[ "${SKIP_LETS_ENCRYPT}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
42 log_f "SKIP_LETS_ENCRYPT=y, skipping Let's Encrypt..."
43 sleep 365d
44 exec $(readlink -f "$0")
45fi
46
47log_f "Waiting for Docker API..."
48until ping dockerapi -c1 > /dev/null; do
49 sleep 1
50done
51log_f "Docker API OK"
52
53log_f "Waiting for Postfix..."
54until ping postfix -c1 > /dev/null; do
55 sleep 1
56done
57log_f "Postfix OK"
58
59log_f "Waiting for Dovecot..."
60until ping dovecot -c1 > /dev/null; do
61 sleep 1
62done
63log_f "Dovecot OK"
64
65ACME_BASE=/var/lib/acme
66SSL_EXAMPLE=/var/lib/ssl-example
67
68mkdir -p ${ACME_BASE}/acme
69
70# Migrate
71[[ -f ${ACME_BASE}/acme/private/privkey.pem ]] && mv ${ACME_BASE}/acme/private/privkey.pem ${ACME_BASE}/acme/key.pem
72[[ -f ${ACME_BASE}/acme/private/account.key ]] && mv ${ACME_BASE}/acme/private/account.key ${ACME_BASE}/acme/account.pem
73if [[ -f ${ACME_BASE}/acme/key.pem && -f ${ACME_BASE}/acme/cert.pem ]]; then
74 if verify_hash_match ${ACME_BASE}/acme/cert.pem ${ACME_BASE}/acme/key.pem; then
75 log_f "Migrating to SNI folder structure..."
76 CERT_DOMAIN=($(openssl x509 -noout -text -in ${ACME_BASE}/acme/cert.pem | grep "Subject:" | sed -e 's/\(Subject:\)\|\(CN = \)\|\(CN=\)//g' | sed -e 's/^[[:space:]]*//'))
77 CERT_DOMAINS=(${CERT_DOMAIN} $(openssl x509 -noout -text -in ${ACME_BASE}/acme/cert.pem | grep "DNS:" | sed -e 's/\(DNS:\)\|,//g' | sed "s/${CERT_DOMAIN}//" | sed -e 's/^[[:space:]]*//'))
78 mkdir -p ${ACME_BASE}/${CERT_DOMAIN}
79 mv ${ACME_BASE}/acme/cert.pem ${ACME_BASE}/${CERT_DOMAIN}/cert.pem
80 # key is only copied, not moved, because it is used by all other requests too
81 cp ${ACME_BASE}/acme/key.pem ${ACME_BASE}/${CERT_DOMAIN}/key.pem
82 chmod 600 ${ACME_BASE}/${CERT_DOMAIN}/key.pem
83 echo -n ${CERT_DOMAINS[*]} > ${ACME_BASE}/${CERT_DOMAIN}/domains
84 mv ${ACME_BASE}/acme/acme.csr ${ACME_BASE}/${CERT_DOMAIN}/acme.csr
85 log_f "OK" no_date
86 fi
87fi
88
89[[ ! -f ${ACME_BASE}/dhparams.pem ]] && cp ${SSL_EXAMPLE}/dhparams.pem ${ACME_BASE}/dhparams.pem
90
91if [[ -f ${ACME_BASE}/cert.pem ]] && [[ -f ${ACME_BASE}/key.pem ]] && [[ $(stat -c%s ${ACME_BASE}/cert.pem) != 0 ]]; then
92 ISSUER=$(openssl x509 -in ${ACME_BASE}/cert.pem -noout -issuer)
93 if [[ ${ISSUER} != *"Let's Encrypt"* && ${ISSUER} != *"mailcow"* && ${ISSUER} != *"Fake LE Intermediate"* ]]; then
94 log_f "Found certificate with issuer other than mailcow snake-oil CA and Let's Encrypt, skipping ACME client..."
95 sleep 3650d
96 exec $(readlink -f "$0")
97 fi
98else
99 if [[ -f ${ACME_BASE}/${MAILCOW_HOSTNAME}/cert.pem ]] && [[ -f ${ACME_BASE}/${MAILCOW_HOSTNAME}/key.pem ]] && verify_hash_match ${ACME_BASE}/${MAILCOW_HOSTNAME}/cert.pem ${ACME_BASE}/${MAILCOW_HOSTNAME}/key.pem; then
100 log_f "Restoring previous acme certificate and restarting script..."
101 cp ${ACME_BASE}/${MAILCOW_HOSTNAME}/cert.pem ${ACME_BASE}/cert.pem
102 cp ${ACME_BASE}/${MAILCOW_HOSTNAME}/key.pem ${ACME_BASE}/key.pem
103 # Restarting with env var set to trigger a restart,
104 exec env TRIGGER_RESTART=1 $(readlink -f "$0")
105 else
106 log_f "Restoring mailcow snake-oil certificates and restarting script..."
107 cp ${SSL_EXAMPLE}/cert.pem ${ACME_BASE}/cert.pem
108 cp ${SSL_EXAMPLE}/key.pem ${ACME_BASE}/key.pem
109 exec env TRIGGER_RESTART=1 $(readlink -f "$0")
110 fi
111fi
112
113chmod 600 ${ACME_BASE}/key.pem
114
115log_f "Waiting for database..."
116while ! mysqladmin status --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent > /dev/null; do
117 sleep 2
118done
119log_f "Database OK"
120
121log_f "Waiting for Nginx..."
122until $(curl --output /dev/null --silent --head --fail http://nginx:8081); do
123 sleep 2
124done
125log_f "Nginx OK"
126
127log_f "Waiting for resolver..."
128until dig letsencrypt.org +time=3 +tries=1 @unbound > /dev/null; do
129 sleep 2
130done
131log_f "Resolver OK"
132
133# Waiting for domain table
134log_f "Waiting for domain table..."
135while [[ -z ${DOMAIN_TABLE} ]]; do
136 curl --silent http://nginx/ >/dev/null 2>&1
137 DOMAIN_TABLE=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SHOW TABLES LIKE 'domain'" -Bs)
138 [[ -z ${DOMAIN_TABLE} ]] && sleep 10
139done
140log_f "OK" no_date
141
142log_f "Initializing, please wait..."
143
144while true; do
145 POSTFIX_CERT_SERIAL="$(echo | openssl s_client -connect postfix:25 -starttls smtp 2>/dev/null | openssl x509 -inform pem -noout -serial | cut -d "=" -f 2)"
146 DOVECOT_CERT_SERIAL="$(echo | openssl s_client -connect dovecot:143 -starttls imap 2>/dev/null | openssl x509 -inform pem -noout -serial | cut -d "=" -f 2)"
147 POSTFIX_CERT_SERIAL_NEW="$(echo | openssl s_client -connect postfix:25 -starttls smtp 2>/dev/null | openssl x509 -inform pem -noout -serial | cut -d "=" -f 2)"
148 DOVECOT_CERT_SERIAL_NEW="$(echo | openssl s_client -connect dovecot:143 -starttls imap 2>/dev/null | openssl x509 -inform pem -noout -serial | cut -d "=" -f 2)"
149 # Re-using previous acme-mailcow account and domain keys
150 if [[ ! -f ${ACME_BASE}/acme/key.pem ]]; then
151 log_f "Generating missing domain private rsa key..."
152 openssl genrsa 4096 > ${ACME_BASE}/acme/key.pem
153 else
154 log_f "Using existing domain rsa key ${ACME_BASE}/acme/key.pem"
155 fi
156 if [[ ! -f ${ACME_BASE}/acme/account.pem ]]; then
157 log_f "Generating missing Lets Encrypt account key..."
158 openssl genrsa 4096 > ${ACME_BASE}/acme/account.pem
159 else
160 log_f "Using existing Lets Encrypt account key ${ACME_BASE}/acme/account.pem"
161 fi
162
163 chmod 600 ${ACME_BASE}/acme/key.pem
164 chmod 600 ${ACME_BASE}/acme/account.pem
165
166 unset EXISTING_CERTS
167 declare -a EXISTING_CERTS
168 for cert_dir in ${ACME_BASE}/*/ ; do
169 if [[ ! -f ${cert_dir}domains ]] || [[ ! -f ${cert_dir}cert.pem ]] || [[ ! -f ${cert_dir}key.pem ]]; then
170 continue
171 fi
172 EXISTING_CERTS+=("$(basename ${cert_dir})")
173 done
174
175 # Cleaning up and init validation arrays
176 unset SQL_DOMAIN_ARR
177 unset VALIDATED_CONFIG_DOMAINS
178 unset ADDITIONAL_VALIDATED_SAN
179 unset ADDITIONAL_WC_ARR
180 unset ADDITIONAL_SAN_ARR
181 unset CERT_ERRORS
182 unset CERT_CHANGED
183 unset CERT_AMOUNT_CHANGED
184 unset VALIDATED_CERTIFICATES
185 CERT_ERRORS=0
186 CERT_CHANGED=0
187 CERT_AMOUNT_CHANGED=0
188 declare -a SQL_DOMAIN_ARR
189 declare -a VALIDATED_CONFIG_DOMAINS
190 declare -a ADDITIONAL_VALIDATED_SAN
191 declare -a ADDITIONAL_WC_ARR
192 declare -a ADDITIONAL_SAN_ARR
193 declare -a VALIDATED_CERTIFICATES
194 IFS=',' read -r -a TMP_ARR <<< "${ADDITIONAL_SAN}"
195 for i in "${TMP_ARR[@]}" ; do
196 if [[ "$i" =~ \.\*$ ]]; then
197 ADDITIONAL_WC_ARR+=(${i::-2})
198 else
199 ADDITIONAL_SAN_ARR+=($i)
200 fi
201 done
202 ADDITIONAL_WC_ARR+=('autodiscover' 'autoconfig')
203
204 # Start IP detection
205 log_f "Detecting IP addresses..."
206 IPV4=$(get_ipv4)
207 IPV6=$(get_ipv6)
208 log_f "OK: ${IPV4}, ${IPV6:-"0000:0000:0000:0000:0000:0000:0000:0000"}"
209
210 # Hard-fail on CAA errors for MAILCOW_HOSTNAME
211 MH_PARENT_DOMAIN=$(echo ${MAILCOW_HOSTNAME} | cut -d. -f2-)
212 MH_CAAS=( $(dig CAA ${MH_PARENT_DOMAIN} +short | sed -n 's/\d issue "\(.*\)"/\1/p') )
213 if [[ ! -z ${MH_CAAS} ]]; then
214 if [[ ${MH_CAAS[@]} =~ "letsencrypt.org" ]]; then
215 log_f "Validated CAA for parent domain ${MH_PARENT_DOMAIN}"
216 else
217 log_f "Skipping ACME validation: Lets Encrypt disallowed for ${MAILCOW_HOSTNAME} by CAA record, retrying in 1h..."
218 sleep 1h
219 exec $(readlink -f "$0")
220 fi
221 fi
222
223 #########################################
224 # IP and webroot challenge verification #
225 SQL_DOMAINS=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SELECT domain FROM domain WHERE backupmx=0" -Bs)
226 if [[ ! $? -eq 0 ]]; then
227 log_f "Failed to read SQL domains, retrying in 1 minute..."
228 sleep 1m
229 exec $(readlink -f "$0")
230 fi
231 while read domains; do
232 if [[ -z "${domains}" ]]; then
233 # ignore empty lines
234 continue
235 fi
236 SQL_DOMAIN_ARR+=("${domains}")
237 done <<< "${SQL_DOMAINS}"
238
239 if [[ ${ONLY_MAILCOW_HOSTNAME} != "y" ]]; then
240 for SQL_DOMAIN in "${SQL_DOMAIN_ARR[@]}"; do
241 unset VALIDATED_CONFIG_DOMAINS_SUBDOMAINS
242 declare -a VALIDATED_CONFIG_DOMAINS_SUBDOMAINS
243 for SUBDOMAIN in "${ADDITIONAL_WC_ARR[@]}"; do
244 if [[ "${SUBDOMAIN}.${SQL_DOMAIN}" != "${MAILCOW_HOSTNAME}" ]]; then
245 if check_domain "${SUBDOMAIN}.${SQL_DOMAIN}"; then
246 VALIDATED_CONFIG_DOMAINS_SUBDOMAINS+=("${SUBDOMAIN}.${SQL_DOMAIN}")
247 fi
248 fi
249 done
250 VALIDATED_CONFIG_DOMAINS+=("${VALIDATED_CONFIG_DOMAINS_SUBDOMAINS[*]}")
251 done
252 fi
253
254 if check_domain ${MAILCOW_HOSTNAME}; then
255 VALIDATED_MAILCOW_HOSTNAME="${MAILCOW_HOSTNAME}"
256 fi
257
258 if [[ ${ONLY_MAILCOW_HOSTNAME} != "y" ]]; then
259 for SAN in "${ADDITIONAL_SAN_ARR[@]}"; do
260 # Skip on CAA errors for SAN
261 SAN_PARENT_DOMAIN=$(echo ${SAN} | cut -d. -f2-)
262 SAN_CAAS=( $(dig CAA ${SAN_PARENT_DOMAIN} +short | sed -n 's/\d issue "\(.*\)"/\1/p') )
263 if [[ ! -z ${SAN_CAAS} ]]; then
264 if [[ ${SAN_CAAS[@]} =~ "letsencrypt.org" ]]; then
265 log_f "Validated CAA for parent domain ${SAN_PARENT_DOMAIN} of ${SAN}"
266 else
267 log_f "Skipping ACME validation for ${SAN}: Lets Encrypt disallowed for ${SAN} by CAA record"
268 continue
269 fi
270 fi
271 if [[ ${SAN} == ${MAILCOW_HOSTNAME} ]]; then
272 continue
273 fi
274 if check_domain ${SAN}; then
275 ADDITIONAL_VALIDATED_SAN+=("${SAN}")
276 fi
277 done
278 fi
279
280 # Unique domains for server certificate
281 if [[ ${ENABLE_SSL_SNI} == "y" ]]; then
282 # create certificate for server name and fqdn SANs only
283 SERVER_SAN_VALIDATED=(${VALIDATED_MAILCOW_HOSTNAME} $(echo ${ADDITIONAL_VALIDATED_SAN[*]} | xargs -n1 | sort -u | xargs))
284 else
285 # create certificate for all domains, including all subdomains from other domains [*]
286 SERVER_SAN_VALIDATED=(${VALIDATED_MAILCOW_HOSTNAME} $(echo ${VALIDATED_CONFIG_DOMAINS[*]} ${ADDITIONAL_VALIDATED_SAN[*]} | xargs -n1 | sort -u | xargs))
287 fi
288 if [[ ! -z ${SERVER_SAN_VALIDATED[*]} ]]; then
289 CERT_NAME=${SERVER_SAN_VALIDATED[0]}
290 VALIDATED_CERTIFICATES+=("${CERT_NAME}")
291
292 # obtain server certificate if required
293 DOMAINS=${SERVER_SAN_VALIDATED[@]} /srv/obtain-certificate.sh rsa
294 RETURN="$?"
295 if [[ "$RETURN" == "0" ]]; then # 0 = cert created successfully
296 CERT_AMOUNT_CHANGED=1
297 CERT_CHANGED=1
298 elif [[ "$RETURN" == "1" ]]; then # 1 = cert renewed successfully
299 CERT_CHANGED=1
300 elif [[ "$RETURN" == "2" ]]; then # 2 = cert not due for renewal
301 :
302 else
303 CERT_ERRORS=1
304 fi
305 # copy hostname certificate to default/server certificate
306 # do not a key when cert is missing, this can lead to a mismatch of cert/key
307 if [[ -f ${ACME_BASE}/${CERT_NAME}/cert.pem ]]; then
308 cp ${ACME_BASE}/${CERT_NAME}/cert.pem ${ACME_BASE}/cert.pem
309 cp ${ACME_BASE}/${CERT_NAME}/key.pem ${ACME_BASE}/key.pem
310 fi
311 fi
312
313 # individual certificates for SNI [@]
314 if [[ ${ENABLE_SSL_SNI} == "y" ]]; then
315 for VALIDATED_DOMAINS in "${VALIDATED_CONFIG_DOMAINS[@]}"; do
316 VALIDATED_DOMAINS_ARR=(${VALIDATED_DOMAINS})
317
318 unset VALIDATED_DOMAINS_SORTED
319 declare -a VALIDATED_DOMAINS_SORTED
320 VALIDATED_DOMAINS_SORTED=(${VALIDATED_DOMAINS_ARR[0]} $(echo ${VALIDATED_DOMAINS_ARR[@]:1} | xargs -n1 | sort -u | xargs))
321
322 # remove all domain names that are already inside the server certificate (SERVER_SAN_VALIDATED)
323 for domain in "${SERVER_SAN_VALIDATED[@]}"; do
324 for i in "${!VALIDATED_DOMAINS_SORTED[@]}"; do
325 if [[ ${VALIDATED_DOMAINS_SORTED[i]} = $domain ]]; then
326 unset 'VALIDATED_DOMAINS_SORTED[i]'
327 fi
328 done
329 done
330
331 if [[ ! -z ${VALIDATED_DOMAINS_SORTED[*]} ]]; then
332 CERT_NAME=${VALIDATED_DOMAINS_SORTED[0]}
333 VALIDATED_CERTIFICATES+=("${CERT_NAME}")
334 # obtain certificate if required
335 DOMAINS=${VALIDATED_DOMAINS_SORTED[@]} /srv/obtain-certificate.sh rsa
336 RETURN="$?"
337 if [[ "$RETURN" == "0" ]]; then # 0 = cert created successfully
338 CERT_AMOUNT_CHANGED=1
339 CERT_CHANGED=1
340 elif [[ "$RETURN" == "1" ]]; then # 1 = cert renewed successfully
341 CERT_CHANGED=1
342 elif [[ "$RETURN" == "2" ]]; then # 2 = cert not due for renewal
343 :
344 else
345 CERT_ERRORS=1
346 fi
347 fi
348 done
349 fi
350
351 if [[ -z ${VALIDATED_CERTIFICATES[*]} ]]; then
352 log_f "Cannot validate any hostnames, skipping Let's Encrypt for 1 hour."
353 log_f "Use SKIP_LETS_ENCRYPT=y in mailcow.conf to skip it permanently."
354 ${REDIS_CMDLINE} SET ACME_FAIL_TIME "$(date +%s)"
355 sleep 1h
356 exec $(readlink -f "$0")
357 fi
358
359 # find orphaned certificates if no errors occurred
360 if [[ "${CERT_ERRORS}" == "0" ]]; then
361 for EXISTING_CERT in "${EXISTING_CERTS[@]}"; do
362 if [[ ! "`printf '_%s_\n' "${VALIDATED_CERTIFICATES[@]}"`" == *"_${EXISTING_CERT}_"* ]]; then
363 DATE=$(date +%Y-%m-%d_%H_%M_%S)
364 log_f "Found orphaned certificate: ${EXISTING_CERT} - archiving it at ${ACME_BASE}/backups/${EXISTING_CERT}/"
365 BACKUP_DIR=${ACME_BASE}/backups/${EXISTING_CERT}/${DATE}
366 # archive rsa cert and any other files
367 mkdir -p ${ACME_BASE}/backups/${EXISTING_CERT}
368 mv ${ACME_BASE}/${EXISTING_CERT} ${BACKUP_DIR}
369 CERT_CHANGED=1
370 CERT_AMOUNT_CHANGED=1
371 fi
372 done
373 fi
374
375 # reload on new or changed certificates
376 if [[ "${CERT_CHANGED}" == "1" ]]; then
377 rm -f "${ACME_BASE}/force_renew" 2> /dev/null
378 RELOAD_LOOP_C=1
379 while [[ "${POSTFIX_CERT_SERIAL}" == "${POSTFIX_CERT_SERIAL_NEW}" ]] || [[ "${DOVECOT_CERT_SERIAL}" == "${DOVECOT_CERT_SERIAL_NEW}" ]] || [[ ${#POSTFIX_CERT_SERIAL_NEW} -ne 36 ]] || [[ ${#DOVECOT_CERT_SERIAL_NEW} -ne 36 ]]; do
380 log_f "Reloading or restarting services... (${RELOAD_LOOP_C})"
381 RELOAD_LOOP_C=$((RELOAD_LOOP_C + 1))
382 CERT_AMOUNT_CHANGED=${CERT_AMOUNT_CHANGED} /srv/reload-configurations.sh
383 log_f "Waiting for containers to settle..."
384 sleep 10
385 until nc -z dovecot 143; do
386 sleep 1
387 done
388 until nc -z postfix 25; do
389 sleep 1
390 done
391 POSTFIX_CERT_SERIAL_NEW="$(echo | openssl s_client -connect postfix:25 -starttls smtp 2>/dev/null | openssl x509 -inform pem -noout -serial | cut -d "=" -f 2)"
392 DOVECOT_CERT_SERIAL_NEW="$(echo | openssl s_client -connect dovecot:143 -starttls imap 2>/dev/null | openssl x509 -inform pem -noout -serial | cut -d "=" -f 2)"
393 if [[ ${RELOAD_LOOP_C} -gt 3 ]]; then
394 log_f "Some services do return old end dates, something went wrong!"
395 ${REDIS_CMDLINE} SET ACME_FAIL_TIME "$(date +%s)"
396 break;
397 fi
398 done
399 fi
400
401 case "$CERT_ERRORS" in
402 0) # all successful
403 if [[ "${CERT_CHANGED}" == "1" ]]; then
404 if [[ "${CERT_AMOUNT_CHANGED}" == "1" ]]; then
405 log_f "Certificates successfully requested and renewed where required, sleeping one day"
406 else
407 log_f "Certificates were successfully renewed where required, sleeping for another day."
408 fi
409 else
410 log_f "Certificates were successfully validated, no changes or renewals required, sleeping for another day."
411 fi
412 sleep 1d
413 ;;
414 *) # non-zero
415 log_f "Some errors occurred, retrying in 30 minutes..."
416 ${REDIS_CMDLINE} SET ACME_FAIL_TIME "$(date +%s)"
417 sleep 30m
418 exec $(readlink -f "$0")
419 ;;
420 esac
421
422done