docker-entrypoint.sh 15 KB

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