docker-entrypoint.sh 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 listescape mail_crypt mail_crypt_acl mail_log notify replication' > /etc/dovecot/mail_plugins
  102. echo -n 'quota imap_quota imap_acl acl zlib imap_zlib imap_sieve listescape mail_crypt mail_crypt_acl notify replication mail_log' > /etc/dovecot/mail_plugins_imap
  103. echo -n 'quota sieve acl zlib listescape mail_crypt mail_crypt_acl notify replication' > /etc/dovecot/mail_plugins_lmtp
  104. else
  105. echo -n 'quota acl zlib listescape mail_crypt mail_crypt_acl mail_log notify fts fts_solr replication' > /etc/dovecot/mail_plugins
  106. echo -n 'quota imap_quota imap_acl acl zlib imap_zlib imap_sieve listescape mail_crypt mail_crypt_acl notify mail_log fts fts_solr replication' > /etc/dovecot/mail_plugins_imap
  107. echo -n 'quota sieve acl zlib listescape mail_crypt mail_crypt_acl fts fts_solr notify 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. # Create pass dict for Dovecot
  118. cat <<EOF > /etc/dovecot/sql/dovecot-dict-sql-passdb.conf
  119. # Autogenerated by mailcow
  120. driver = mysql
  121. connect = "host=/var/run/mysqld/mysqld.sock dbname=${DBNAME} user=${DBUSER} password=${DBPASS}"
  122. default_pass_scheme = ${MAILCOW_PASS_SCHEME}
  123. password_query = SELECT password FROM mailbox WHERE active = '1' AND username = '%u' AND domain IN (SELECT domain FROM domain WHERE domain='%d' AND active='1') AND JSON_UNQUOTE(JSON_VALUE(attributes, '$.force_pw_update')) != '1' AND (JSON_UNQUOTE(JSON_VALUE(attributes, '$.%s_access')) = '1' OR ('%s' != 'imap' AND '%s' != 'pop3'))
  124. EOF
  125. cat <<EOF > /etc/dovecot/lua/passwd-verify.lua
  126. function auth_password_verify(req, pass)
  127. if req.domain == nil then
  128. return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "No such user"
  129. end
  130. if cur == nil then
  131. script_init()
  132. end
  133. if req.user == nil then
  134. req.user = ''
  135. end
  136. respbody = {}
  137. -- check against mailbox passwds
  138. local cur,errorString = con:execute(string.format([[SELECT password FROM mailbox
  139. WHERE username = '%s'
  140. AND active = '1'
  141. AND domain IN (SELECT domain FROM domain WHERE domain='%s' AND active='1')
  142. AND IFNULL(JSON_UNQUOTE(JSON_VALUE(attributes, '$.%s_access')), 1) = '1']], con:escape(req.user), con:escape(req.domain), con:escape(req.service)))
  143. local row = cur:fetch ({}, "a")
  144. while row do
  145. if req.password_verify(req, row.password, pass) == 1 then
  146. cur:close()
  147. con:execute(string.format([[INSERT INTO sasl_logs (success, service, app_password, username, real_rip)
  148. VALUES (1, "%s", 0, "%s", "%s")]], con:escape(req.service), con:escape(req.user), con:escape(req.real_rip)))
  149. return dovecot.auth.PASSDB_RESULT_OK, "password=" .. pass
  150. end
  151. row = cur:fetch (row, "a")
  152. end
  153. -- check against app passwds
  154. local cur,errorString = con:execute(string.format([[SELECT app_passwd.id, app_passwd.password FROM app_passwd
  155. INNER JOIN mailbox ON mailbox.username = app_passwd.mailbox
  156. WHERE mailbox = '%s'
  157. AND IFNULL(JSON_UNQUOTE(JSON_VALUE(mailbox.attributes, '$.%s_access')), 1) = '1'
  158. AND app_passwd.active = '1'
  159. AND mailbox.active = '1'
  160. AND app_passwd.domain IN (SELECT domain FROM domain WHERE domain='%s' AND active='1')]], con:escape(req.user), con:escape(req.service), con:escape(req.domain)))
  161. local row = cur:fetch ({}, "a")
  162. while row do
  163. if req.password_verify(req, row.password, pass) == 1 then
  164. cur:close()
  165. con:execute(string.format([[INSERT INTO sasl_logs (success, service, app_password, username, real_rip)
  166. VALUES (1, "%s", %d, "%s", "%s")]], con:escape(req.service), row.id, con:escape(req.user), con:escape(req.real_rip)))
  167. return dovecot.auth.PASSDB_RESULT_OK, "password=" .. pass
  168. end
  169. row = cur:fetch (row, "a")
  170. end
  171. con:execute(string.format([[INSERT INTO sasl_logs (success, service, app_password, username, real_rip)
  172. VALUES (0, "%s", 0, "%s", "%s")]], con:escape(req.service), con:escape(req.user), con:escape(req.real_rip)))
  173. return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Failed to authenticate"
  174. -- PoC
  175. -- local reqbody = string.format([[{
  176. -- "success":0,
  177. -- "service":"%s",
  178. -- "app_password":false,
  179. -- "username":"%s",
  180. -- "real_rip":"%s"
  181. -- }]], con:escape(req.service), con:escape(req.user), con:escape(req.real_rip))
  182. -- http.request {
  183. -- method = "POST",
  184. -- url = "http://nginx:8081/sasl_logs.php",
  185. -- source = ltn12.source.string(reqbody),
  186. -- headers = {
  187. -- ["content-type"] = "application/json",
  188. -- ["content-length"] = tostring(#reqbody)
  189. -- },
  190. -- sink = ltn12.sink.table(respbody)
  191. -- }
  192. end
  193. function auth_passdb_lookup(req)
  194. return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, ""
  195. end
  196. function script_init()
  197. mysql = require "luasql.mysql"
  198. http = require "socket.http"
  199. http.TIMEOUT = 5
  200. ltn12 = require "ltn12"
  201. env = mysql.mysql()
  202. con = env:connect("__DBNAME__","__DBUSER__","__DBPASS__","localhost")
  203. return 0
  204. end
  205. function script_deinit()
  206. con:close()
  207. env:close()
  208. end
  209. EOF
  210. # Replace patterns in app-passdb.lua
  211. sed -i "s/__DBUSER__/${DBUSER}/g" /etc/dovecot/lua/passwd-verify.lua
  212. sed -i "s/__DBPASS__/${DBPASS}/g" /etc/dovecot/lua/passwd-verify.lua
  213. sed -i "s/__DBNAME__/${DBNAME}/g" /etc/dovecot/lua/passwd-verify.lua
  214. # Migrate old sieve_after file
  215. [[ -f /etc/dovecot/sieve_after ]] && mv /etc/dovecot/sieve_after /etc/dovecot/global_sieve_after
  216. # Create global sieve scripts
  217. cat /etc/dovecot/global_sieve_after > /var/vmail/sieve/global_sieve_after.sieve
  218. cat /etc/dovecot/global_sieve_before > /var/vmail/sieve/global_sieve_before.sieve
  219. # Check permissions of vmail/index/garbage directories.
  220. # Do not do this every start-up, it may take a very long time. So we use a stat check here.
  221. if [[ $(stat -c %U /var/vmail/) != "vmail" ]] ; then chown -R vmail:vmail /var/vmail ; fi
  222. if [[ $(stat -c %U /var/vmail/_garbage) != "vmail" ]] ; then chown -R vmail:vmail /var/vmail/_garbage ; fi
  223. if [[ $(stat -c %U /var/vmail_index) != "vmail" ]] ; then chown -R vmail:vmail /var/vmail_index ; fi
  224. # Cleanup random user maildirs
  225. rm -rf /var/vmail/mailcow.local/*
  226. # Cleanup PIDs
  227. [[ -f /tmp/quarantine_notify.pid ]] && rm /tmp/quarantine_notify.pid
  228. # create sni configuration
  229. echo "" > /etc/dovecot/sni.conf
  230. for cert_dir in /etc/ssl/mail/*/ ; do
  231. if [[ ! -f ${cert_dir}domains ]] || [[ ! -f ${cert_dir}cert.pem ]] || [[ ! -f ${cert_dir}key.pem ]]; then
  232. continue
  233. fi
  234. domains=($(cat ${cert_dir}domains))
  235. for domain in ${domains[@]}; do
  236. echo 'local_name '${domain}' {' >> /etc/dovecot/sni.conf;
  237. echo ' ssl_cert = <'${cert_dir}'cert.pem' >> /etc/dovecot/sni.conf;
  238. echo ' ssl_key = <'${cert_dir}'key.pem' >> /etc/dovecot/sni.conf;
  239. echo '}' >> /etc/dovecot/sni.conf;
  240. done
  241. done
  242. # Create random master for SOGo sieve features
  243. RAND_USER=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 16 | head -n 1)
  244. RAND_PASS=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 24 | head -n 1)
  245. if [[ ! -z ${DOVECOT_MASTER_USER} ]] && [[ ! -z ${DOVECOT_MASTER_PASS} ]]; then
  246. RAND_USER=${DOVECOT_MASTER_USER}
  247. RAND_PASS=${DOVECOT_MASTER_PASS}
  248. fi
  249. echo ${RAND_USER}@mailcow.local:{SHA1}$(echo -n ${RAND_PASS} | sha1sum | awk '{print $1}'):::::: > /etc/dovecot/dovecot-master.passwd
  250. echo ${RAND_USER}@mailcow.local::5000:5000:::: > /etc/dovecot/dovecot-master.userdb
  251. echo ${RAND_USER}@mailcow.local:${RAND_PASS} > /etc/sogo/sieve.creds
  252. if [[ -z ${MAILDIR_SUB} ]]; then
  253. MAILDIR_SUB_SHARED=
  254. else
  255. MAILDIR_SUB_SHARED=/${MAILDIR_SUB}
  256. fi
  257. cat <<EOF > /etc/dovecot/shared_namespace.conf
  258. # Autogenerated by mailcow
  259. namespace {
  260. type = shared
  261. separator = /
  262. prefix = Shared/%%u/
  263. location = maildir:%%h${MAILDIR_SUB_SHARED}:INDEX=~${MAILDIR_SUB_SHARED}/Shared/%%u
  264. subscriptions = no
  265. list = children
  266. }
  267. EOF
  268. cat <<EOF > /etc/dovecot/sogo_trusted_ip.conf
  269. # Autogenerated by mailcow
  270. remote ${IPV4_NETWORK}.248 {
  271. disable_plaintext_auth = no
  272. }
  273. EOF
  274. if [[ "${ALLOW_ADMIN_EMAIL_LOGIN}" =~ ^([yY][eE][sS]|[yY])+$ ]]; then
  275. # Create random master Password for SOGo 'login as user' via proxy auth
  276. RAND_PASS=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 32 | head -n 1)
  277. echo -n ${RAND_PASS} > /etc/phpfpm/sogo-sso.pass
  278. cat <<EOF > /etc/dovecot/sogo-sso.conf
  279. # Autogenerated by mailcow
  280. passdb {
  281. driver = static
  282. args = allow_real_nets=${IPV4_NETWORK}.248/32 password={plain}${RAND_PASS}
  283. }
  284. EOF
  285. else
  286. rm -f /etc/dovecot/sogo-sso.pass
  287. rm -f /etc/dovecot/sogo-sso.conf
  288. fi
  289. if [[ "${MASTER}" =~ ^([nN][oO]|[nN])+$ ]]; then
  290. # Toggling MASTER will result in a rebuild of containers, so the quota script will be recreated
  291. cat <<'EOF' > /usr/local/bin/quota_notify.py
  292. #!/usr/bin/python3
  293. import sys
  294. sys.exit()
  295. EOF
  296. fi
  297. # 401 is user dovecot
  298. if [[ ! -s /mail_crypt/ecprivkey.pem || ! -s /mail_crypt/ecpubkey.pem ]]; then
  299. openssl ecparam -name prime256v1 -genkey | openssl pkey -out /mail_crypt/ecprivkey.pem
  300. openssl pkey -in /mail_crypt/ecprivkey.pem -pubout -out /mail_crypt/ecpubkey.pem
  301. chown 401 /mail_crypt/ecprivkey.pem /mail_crypt/ecpubkey.pem
  302. else
  303. chown 401 /mail_crypt/ecprivkey.pem /mail_crypt/ecpubkey.pem
  304. fi
  305. # Compile sieve scripts
  306. sievec /var/vmail/sieve/global_sieve_before.sieve
  307. sievec /var/vmail/sieve/global_sieve_after.sieve
  308. sievec /usr/lib/dovecot/sieve/report-spam.sieve
  309. sievec /usr/lib/dovecot/sieve/report-ham.sieve
  310. # Fix permissions
  311. chown root:root /etc/dovecot/sql/*.conf
  312. chown root:dovecot /etc/dovecot/sql/dovecot-dict-sql-sieve* /etc/dovecot/sql/dovecot-dict-sql-quota* /etc/dovecot/lua/passwd-verify.lua
  313. chmod 640 /etc/dovecot/sql/*.conf /etc/dovecot/lua/passwd-verify.lua
  314. chown -R vmail:vmail /var/vmail/sieve
  315. chown -R vmail:vmail /var/volatile
  316. chown -R vmail:vmail /var/vmail_index
  317. adduser vmail tty
  318. chmod g+rw /dev/console
  319. chown root:tty /dev/console
  320. chmod +x /usr/lib/dovecot/sieve/rspamd-pipe-ham \
  321. /usr/lib/dovecot/sieve/rspamd-pipe-spam \
  322. /usr/local/bin/imapsync_runner.pl \
  323. /usr/local/bin/imapsync \
  324. /usr/local/bin/trim_logs.sh \
  325. /usr/local/bin/sa-rules.sh \
  326. /usr/local/bin/clean_q_aged.sh \
  327. /usr/local/bin/maildir_gc.sh \
  328. /usr/local/sbin/stop-supervisor.sh \
  329. /usr/local/bin/quota_notify.py \
  330. /usr/local/bin/repl_health.sh
  331. # Prepare environment file for cronjobs
  332. printenv | sed 's/^\(.*\)$/export \1/g' > /source_env.sh
  333. # Clean old PID if any
  334. [[ -f /var/run/dovecot/master.pid ]] && rm /var/run/dovecot/master.pid
  335. # Clean stopped imapsync jobs
  336. rm -f /tmp/imapsync_busy.lock
  337. IMAPSYNC_TABLE=$(mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "SHOW TABLES LIKE 'imapsync'" -Bs)
  338. [[ ! -z ${IMAPSYNC_TABLE} ]] && mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} -e "UPDATE imapsync SET is_running='0'"
  339. # Envsubst maildir_gc
  340. echo "$(envsubst < /usr/local/bin/maildir_gc.sh)" > /usr/local/bin/maildir_gc.sh
  341. # GUID generation
  342. while [[ ${VERSIONS_OK} != 'OK' ]]; do
  343. 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
  344. VERSIONS_OK=OK
  345. else
  346. echo "Waiting for versions table to be created..."
  347. sleep 3
  348. fi
  349. done
  350. PUBKEY_MCRYPT=$(doveconf -P 2> /dev/null | grep -i mail_crypt_global_public_key | cut -d '<' -f2)
  351. if [ -f ${PUBKEY_MCRYPT} ]; then
  352. GUID=$(cat <(echo ${MAILCOW_HOSTNAME}) /mail_crypt/ecpubkey.pem | sha256sum | cut -d ' ' -f1 | tr -cd "[a-fA-F0-9.:/] ")
  353. if [ ${#GUID} -eq 64 ]; then
  354. mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF
  355. REPLACE INTO versions (application, version) VALUES ("GUID", "${GUID}");
  356. EOF
  357. else
  358. mysql --socket=/var/run/mysqld/mysqld.sock -u ${DBUSER} -p${DBPASS} ${DBNAME} << EOF
  359. REPLACE INTO versions (application, version) VALUES ("GUID", "INVALID");
  360. EOF
  361. fi
  362. fi
  363. # Collect SA rules once now
  364. /usr/local/bin/sa-rules.sh
  365. # Run hooks
  366. for file in /hooks/*; do
  367. if [ -x "${file}" ]; then
  368. echo "Running hook ${file}"
  369. "${file}"
  370. fi
  371. done
  372. # 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
  373. # May be related to something inside Docker, I seriously don't know
  374. touch /etc/dovecot/lua/passwd-verify.lua
  375. exec "$@"