docker-entrypoint.sh 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. #!/bin/bash
  2. set -e
  3. # Wait for MySQL to warm-up
  4. while ! mysqladmin status --socket=/var/run/mysqld/mysqld.sock -u${DBUSER} -p${DBPASS} --silent; do
  5. echo "Waiting for database to come up..."
  6. sleep 2
  7. done
  8. until dig +short mailcow.email > /dev/null; do
  9. echo "Waiting for DNS..."
  10. sleep 1
  11. done
  12. # Do not attempt to write to slave
  13. if [[ ! -z ${REDIS_SLAVEOF_IP} ]]; then
  14. REDIS_CMDLINE="redis-cli -h ${REDIS_SLAVEOF_IP} -p ${REDIS_SLAVEOF_PORT}"
  15. else
  16. REDIS_CMDLINE="redis-cli -h redis -p 6379"
  17. fi
  18. until [[ $(${REDIS_CMDLINE} PING) == "PONG" ]]; do
  19. echo "Waiting for Redis..."
  20. sleep 2
  21. done
  22. ${REDIS_CMDLINE} SET DOVECOT_REPL_HEALTH 1 > /dev/null
  23. # Create missing directories
  24. [[ ! -d /etc/dovecot/sql/ ]] && mkdir -p /etc/dovecot/sql/
  25. [[ ! -d /etc/dovecot/lua/ ]] && mkdir -p /etc/dovecot/lua/
  26. [[ ! -d /var/vmail/_garbage ]] && mkdir -p /var/vmail/_garbage
  27. [[ ! -d /var/vmail/sieve ]] && mkdir -p /var/vmail/sieve
  28. [[ ! -d /etc/sogo ]] && mkdir -p /etc/sogo
  29. [[ ! -d /var/volatile ]] && mkdir -p /var/volatile
  30. # Set Dovecot sql config parameters, escape " in db password
  31. DBPASS=$(echo ${DBPASS} | sed 's/"/\\"/g')
  32. # Create quota dict for Dovecot
  33. if [[ "${MASTER}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
  34. QUOTA_TABLE=quota2
  35. else
  36. QUOTA_TABLE=quota2replica
  37. fi
  38. cat <<EOF > /etc/dovecot/sql/dovecot-dict-sql-quota.conf
  39. # Autogenerated by mailcow
  40. connect = "host=/var/run/mysqld/mysqld.sock dbname=${DBNAME} user=${DBUSER} password=${DBPASS}"
  41. map {
  42. pattern = priv/quota/storage
  43. table = ${QUOTA_TABLE}
  44. username_field = username
  45. value_field = bytes
  46. }
  47. map {
  48. pattern = priv/quota/messages
  49. table = ${QUOTA_TABLE}
  50. username_field = username
  51. value_field = messages
  52. }
  53. EOF
  54. # Create dict used for sieve pre and postfilters
  55. cat <<EOF > /etc/dovecot/sql/dovecot-dict-sql-sieve_before.conf
  56. # Autogenerated by mailcow
  57. connect = "host=/var/run/mysqld/mysqld.sock dbname=${DBNAME} user=${DBUSER} password=${DBPASS}"
  58. map {
  59. pattern = priv/sieve/name/\$script_name
  60. table = sieve_before
  61. username_field = username
  62. value_field = id
  63. fields {
  64. script_name = \$script_name
  65. }
  66. }
  67. map {
  68. pattern = priv/sieve/data/\$id
  69. table = sieve_before
  70. username_field = username
  71. value_field = script_data
  72. fields {
  73. id = \$id
  74. }
  75. }
  76. EOF
  77. cat <<EOF > /etc/dovecot/sql/dovecot-dict-sql-sieve_after.conf
  78. # Autogenerated by mailcow
  79. connect = "host=/var/run/mysqld/mysqld.sock dbname=${DBNAME} user=${DBUSER} password=${DBPASS}"
  80. map {
  81. pattern = priv/sieve/name/\$script_name
  82. table = sieve_after
  83. username_field = username
  84. value_field = id
  85. fields {
  86. script_name = \$script_name
  87. }
  88. }
  89. map {
  90. pattern = priv/sieve/data/\$id
  91. table = sieve_after
  92. username_field = username
  93. value_field = script_data
  94. fields {
  95. id = \$id
  96. }
  97. }
  98. EOF
  99. echo -n ${ACL_ANYONE} > /etc/dovecot/acl_anyone
  100. if [[ "${SKIP_SOLR}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
  101. echo -n 'quota acl zlib mail_crypt mail_crypt_acl mail_log notify listescape replication' > /etc/dovecot/mail_plugins
  102. echo -n 'quota imap_quota imap_acl acl zlib imap_zlib imap_sieve mail_crypt mail_crypt_acl notify listescape replication mail_log' > /etc/dovecot/mail_plugins_imap
  103. echo -n 'quota sieve acl zlib mail_crypt mail_crypt_acl notify listescape replication' > /etc/dovecot/mail_plugins_lmtp
  104. else
  105. echo -n 'quota acl zlib mail_crypt mail_crypt_acl mail_log notify fts fts_solr listescape replication' > /etc/dovecot/mail_plugins
  106. echo -n 'quota imap_quota imap_acl acl zlib imap_zlib imap_sieve mail_crypt mail_crypt_acl notify mail_log fts fts_solr listescape replication' > /etc/dovecot/mail_plugins_imap
  107. echo -n 'quota sieve acl zlib mail_crypt mail_crypt_acl fts fts_solr notify listescape replication' > /etc/dovecot/mail_plugins_lmtp
  108. fi
  109. chmod 644 /etc/dovecot/mail_plugins /etc/dovecot/mail_plugins_imap /etc/dovecot/mail_plugins_lmtp /templates/quarantine.tpl
  110. cat <<EOF > /etc/dovecot/sql/dovecot-dict-sql-userdb.conf
  111. # Autogenerated by mailcow
  112. driver = mysql
  113. connect = "host=/var/run/mysqld/mysqld.sock dbname=${DBNAME} user=${DBUSER} password=${DBPASS}"
  114. user_query = SELECT CONCAT(JSON_UNQUOTE(JSON_VALUE(attributes, '$.mailbox_format')), mailbox_path_prefix, '%d/%n/${MAILDIR_SUB}:VOLATILEDIR=/var/volatile/%u:INDEX=/var/vmail_index/%u') AS mail, '%s' AS protocol, 5000 AS uid, 5000 AS gid, concat('*:bytes=', quota) AS quota_rule FROM mailbox WHERE username = '%u' AND (active = '1' OR active = '2')
  115. iterate_query = SELECT username FROM mailbox WHERE active = '1' OR active = '2';
  116. EOF
  117. cat <<EOF > /etc/dovecot/lua/passwd-verify.lua
  118. function auth_password_verify(request, password)
  119. if request.domain == nil then
  120. return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "No such user"
  121. end
  122. json = require "json"
  123. ltn12 = require "ltn12"
  124. http = require "socket.http"
  125. http.TIMEOUT = 5
  126. mysql = require "luasql.mysql"
  127. env = mysql.mysql()
  128. con = env:connect("__DBNAME__","__DBUSER__","__DBPASS__","localhost")
  129. local req = {
  130. username = request.user,
  131. password = password
  132. }
  133. local req_json = json.encode(req)
  134. local res = {}
  135. -- check against mailbox passwds
  136. local b, c = http.request {
  137. method = "POST",
  138. url = "https://nginx/api/v1/process/login",
  139. source = ltn12.source.string(req_json),
  140. headers = {
  141. ["content-type"] = "application/json",
  142. ["content-length"] = tostring(#req_json)
  143. },
  144. sink = ltn12.sink.table(res)
  145. }
  146. local api_response = json.decode(table.concat(res))
  147. if api_response.role == 'user' then
  148. con:execute(string.format([[REPLACE INTO sasl_log (service, app_password, username, real_rip)
  149. VALUES ("%s", 0, "%s", "%s")]], con:escape(request.service), con:escape(request.user), con:escape(request.real_rip)))
  150. con:close()
  151. return dovecot.auth.PASSDB_RESULT_OK, "password=" .. password
  152. end
  153. -- check against app passwds for imap and smtp
  154. -- app passwords are only available for imap, smtp, sieve and pop3 when using sasl
  155. if request.service == "smtp" or request.service == "imap" or request.service == "sieve" or request.service == "pop3" then
  156. req.protocol = {}
  157. req.protocol[request.service] = true
  158. req_json = json.encode(req)
  159. req.protocol.ignore_hasaccess = false
  160. if tostring(req.real_rip) == "__IPV4_SOGO__" then
  161. req.protocol.ignore_hasaccess = true
  162. end
  163. local b, c = http.request {
  164. method = "POST",
  165. url = "https://nginx/api/v1/process/login",
  166. source = ltn12.source.string(req_json),
  167. headers = {
  168. ["content-type"] = "application/json",
  169. ["content-length"] = tostring(#req_json)
  170. },
  171. sink = ltn12.sink.table(res)
  172. }
  173. local api_response = json.decode(table.concat(res))
  174. if api_response.role == 'user' then
  175. if req.protocol.ignore_hasaccess == false then
  176. con:execute(string.format([[REPLACE INTO sasl_log (service, app_password, username, real_rip)
  177. VALUES ("%s", %d, "%s", "%s")]], con:escape(req.service), row.id, con:escape(req.user), con:escape(req.real_rip)))
  178. end
  179. con:close()
  180. return dovecot.auth.PASSDB_RESULT_OK, "password=" .. password
  181. end
  182. end
  183. con:close()
  184. return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Failed to authenticate"
  185. end
  186. function auth_passdb_lookup(req)
  187. return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, ""
  188. end
  189. EOF
  190. # Replace patterns in app-passdb.lua
  191. sed -i "s/__DBUSER__/${DBUSER}/g" /etc/dovecot/lua/passwd-verify.lua
  192. sed -i "s/__DBPASS__/${DBPASS}/g" /etc/dovecot/lua/passwd-verify.lua
  193. sed -i "s/__DBNAME__/${DBNAME}/g" /etc/dovecot/lua/passwd-verify.lua
  194. sed -i "s/__IPV4_SOGO__/${IPV4_NETWORK}.248/g" /etc/dovecot/lua/passwd-verify.lua
  195. # Migrate old sieve_after file
  196. [[ -f /etc/dovecot/sieve_after ]] && mv /etc/dovecot/sieve_after /etc/dovecot/global_sieve_after
  197. # Create global sieve scripts
  198. cat /etc/dovecot/global_sieve_after > /var/vmail/sieve/global_sieve_after.sieve
  199. cat /etc/dovecot/global_sieve_before > /var/vmail/sieve/global_sieve_before.sieve
  200. # Check permissions of vmail/index/garbage directories.
  201. # Do not do this every start-up, it may take a very long time. So we use a stat check here.
  202. if [[ $(stat -c %U /var/vmail/) != "vmail" ]] ; then chown -R vmail:vmail /var/vmail ; fi
  203. if [[ $(stat -c %U /var/vmail/_garbage) != "vmail" ]] ; then chown -R vmail:vmail /var/vmail/_garbage ; fi
  204. if [[ $(stat -c %U /var/vmail_index) != "vmail" ]] ; then chown -R vmail:vmail /var/vmail_index ; fi
  205. # Cleanup random user maildirs
  206. rm -rf /var/vmail/mailcow.local/*
  207. # Cleanup PIDs
  208. [[ -f /tmp/quarantine_notify.pid ]] && rm /tmp/quarantine_notify.pid
  209. # create sni configuration
  210. echo "" > /etc/dovecot/sni.conf
  211. for cert_dir in /etc/ssl/mail/*/ ; do
  212. if [[ ! -f ${cert_dir}domains ]] || [[ ! -f ${cert_dir}cert.pem ]] || [[ ! -f ${cert_dir}key.pem ]]; then
  213. continue
  214. fi
  215. domains=($(cat ${cert_dir}domains))
  216. for domain in ${domains[@]}; do
  217. echo 'local_name '${domain}' {' >> /etc/dovecot/sni.conf;
  218. echo ' ssl_cert = <'${cert_dir}'cert.pem' >> /etc/dovecot/sni.conf;
  219. echo ' ssl_key = <'${cert_dir}'key.pem' >> /etc/dovecot/sni.conf;
  220. echo '}' >> /etc/dovecot/sni.conf;
  221. done
  222. done
  223. # Create random master for SOGo sieve features
  224. RAND_USER=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 16 | head -n 1)
  225. RAND_PASS=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 24 | head -n 1)
  226. if [[ ! -z ${DOVECOT_MASTER_USER} ]] && [[ ! -z ${DOVECOT_MASTER_PASS} ]]; then
  227. RAND_USER=${DOVECOT_MASTER_USER}
  228. RAND_PASS=${DOVECOT_MASTER_PASS}
  229. fi
  230. echo ${RAND_USER}@mailcow.local:{SHA1}$(echo -n ${RAND_PASS} | sha1sum | awk '{print $1}'):::::: > /etc/dovecot/dovecot-master.passwd
  231. echo ${RAND_USER}@mailcow.local::5000:5000:::: > /etc/dovecot/dovecot-master.userdb
  232. echo ${RAND_USER}@mailcow.local:${RAND_PASS} > /etc/sogo/sieve.creds
  233. if [[ -z ${MAILDIR_SUB} ]]; then
  234. MAILDIR_SUB_SHARED=
  235. else
  236. MAILDIR_SUB_SHARED=/${MAILDIR_SUB}
  237. fi
  238. cat <<EOF > /etc/dovecot/shared_namespace.conf
  239. # Autogenerated by mailcow
  240. namespace {
  241. type = shared
  242. separator = /
  243. prefix = Shared/%%u/
  244. location = maildir:%%h${MAILDIR_SUB_SHARED}:INDEX=~${MAILDIR_SUB_SHARED}/Shared/%%u
  245. subscriptions = no
  246. list = children
  247. }
  248. EOF
  249. cat <<EOF > /etc/dovecot/sogo_trusted_ip.conf
  250. # Autogenerated by mailcow
  251. remote ${IPV4_NETWORK}.248 {
  252. disable_plaintext_auth = no
  253. }
  254. EOF
  255. # Create random master Password for SOGo SSO
  256. RAND_PASS=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 32 | head -n 1)
  257. echo -n ${RAND_PASS} > /etc/phpfpm/sogo-sso.pass
  258. cat <<EOF > /etc/dovecot/sogo-sso.conf
  259. # Autogenerated by mailcow
  260. passdb {
  261. driver = static
  262. args = allow_real_nets=${IPV4_NETWORK}.248/32 password={plain}${RAND_PASS}
  263. }
  264. EOF
  265. if [[ "${MASTER}" =~ ^([nN][oO]|[nN])+$ ]]; then
  266. # Toggling MASTER will result in a rebuild of containers, so the quota script will be recreated
  267. cat <<'EOF' > /usr/local/bin/quota_notify.py
  268. #!/usr/bin/python3
  269. import sys
  270. sys.exit()
  271. EOF
  272. fi
  273. # Set mail_replica for HA setups
  274. if [[ -n ${MAILCOW_REPLICA_IP} && -n ${DOVEADM_REPLICA_PORT} ]]; then
  275. cat <<EOF > /etc/dovecot/mail_replica.conf
  276. # Autogenerated by mailcow
  277. mail_replica = tcp:${MAILCOW_REPLICA_IP}:${DOVEADM_REPLICA_PORT}
  278. EOF
  279. fi
  280. # 401 is user dovecot
  281. if [[ ! -s /mail_crypt/ecprivkey.pem || ! -s /mail_crypt/ecpubkey.pem ]]; then
  282. openssl ecparam -name prime256v1 -genkey | openssl pkey -out /mail_crypt/ecprivkey.pem
  283. openssl pkey -in /mail_crypt/ecprivkey.pem -pubout -out /mail_crypt/ecpubkey.pem
  284. chown 401 /mail_crypt/ecprivkey.pem /mail_crypt/ecpubkey.pem
  285. else
  286. chown 401 /mail_crypt/ecprivkey.pem /mail_crypt/ecpubkey.pem
  287. fi
  288. # Compile sieve scripts
  289. sievec /var/vmail/sieve/global_sieve_before.sieve
  290. sievec /var/vmail/sieve/global_sieve_after.sieve
  291. sievec /usr/lib/dovecot/sieve/report-spam.sieve
  292. sievec /usr/lib/dovecot/sieve/report-ham.sieve
  293. for file in /var/vmail/*/*/sieve/*.sieve ; do
  294. if [[ "$file" == "/var/vmail/*/*/sieve/*.sieve" ]]; then
  295. continue
  296. fi
  297. sievec "$file" "$(dirname "$file")/../.dovecot.svbin"
  298. chown vmail:vmail "$(dirname "$file")/../.dovecot.svbin"
  299. done
  300. # Fix permissions
  301. chown root:root /etc/dovecot/sql/*.conf
  302. chown root:dovecot /etc/dovecot/sql/dovecot-dict-sql-sieve* /etc/dovecot/sql/dovecot-dict-sql-quota* /etc/dovecot/lua/passwd-verify.lua
  303. chmod 640 /etc/dovecot/sql/*.conf /etc/dovecot/lua/passwd-verify.lua
  304. chown -R vmail:vmail /var/vmail/sieve
  305. chown -R vmail:vmail /var/volatile
  306. chown -R vmail:vmail /var/vmail_index
  307. adduser vmail tty
  308. chmod g+rw /dev/console
  309. chown root:tty /dev/console
  310. chmod +x /usr/lib/dovecot/sieve/rspamd-pipe-ham \
  311. /usr/lib/dovecot/sieve/rspamd-pipe-spam \
  312. /usr/local/bin/imapsync_runner.pl \
  313. /usr/local/bin/imapsync \
  314. /usr/local/bin/trim_logs.sh \
  315. /usr/local/bin/sa-rules.sh \
  316. /usr/local/bin/clean_q_aged.sh \
  317. /usr/local/bin/maildir_gc.sh \
  318. /usr/local/sbin/stop-supervisor.sh \
  319. /usr/local/bin/quota_notify.py \
  320. /usr/local/bin/repl_health.sh
  321. # Prepare environment file for cronjobs
  322. printenv | sed 's/^\(.*\)$/export \1/g' > /source_env.sh
  323. # Clean old PID if any
  324. [[ -f /var/run/dovecot/master.pid ]] && rm /var/run/dovecot/master.pid
  325. # Clean stopped imapsync jobs
  326. rm -f /tmp/imapsync_busy.lock
  327. IMAPSYNC_TABLE=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SHOW TABLES LIKE 'imapsync'" -Bs)
  328. [[ ! -z ${IMAPSYNC_TABLE} ]] && mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "UPDATE imapsync SET is_running='0'"
  329. # Envsubst maildir_gc
  330. echo "$(envsubst < /usr/local/bin/maildir_gc.sh)" > /usr/local/bin/maildir_gc.sh
  331. # GUID generation
  332. while [[ ${VERSIONS_OK} != 'OK' ]]; do
  333. if [[ ! -z $(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -B -e "SELECT 'OK' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = \"${DBNAME}\" AND TABLE_NAME = 'versions'") ]]; then
  334. VERSIONS_OK=OK
  335. else
  336. echo "Waiting for versions table to be created..."
  337. sleep 3
  338. fi
  339. done
  340. PUBKEY_MCRYPT=$(doveconf -P 2> /dev/null | grep -i mail_crypt_global_public_key | cut -d '<' -f2)
  341. if [ -f ${PUBKEY_MCRYPT} ]; then
  342. GUID=$(cat <(echo ${MAILCOW_HOSTNAME}) /mail_crypt/ecpubkey.pem | sha256sum | cut -d ' ' -f1 | tr -cd "[a-fA-F0-9.:/] ")
  343. if [ ${#GUID} -eq 64 ]; then
  344. mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF
  345. REPLACE INTO versions (application, version) VALUES ("GUID", "${GUID}");
  346. EOF
  347. else
  348. mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF
  349. REPLACE INTO versions (application, version) VALUES ("GUID", "INVALID");
  350. EOF
  351. fi
  352. fi
  353. # Collect SA rules once now
  354. /usr/local/bin/sa-rules.sh
  355. # Run hooks
  356. for file in /hooks/*; do
  357. if [ -x "${file}" ]; then
  358. echo "Running hook ${file}"
  359. "${file}"
  360. fi
  361. done
  362. # For some strange, unknown and stupid reason, Dovecot may run into a race condition, when this file is not touched before it is read by dovecot/auth
  363. # May be related to something inside Docker, I seriously don't know
  364. touch /etc/dovecot/lua/passwd-verify.lua
  365. if [[ ! -z ${REDIS_SLAVEOF_IP} ]]; then
  366. cp /etc/syslog-ng/syslog-ng-redis_slave.conf /etc/syslog-ng/syslog-ng.conf
  367. fi
  368. exec "$@"