email_handler.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  1. """
  2. Handle the email *forward* and *reply*. phase. There are 3 actors:
  3. - contact: who sends emails to alias@sl.co address
  4. - SL email handler (this script)
  5. - user personal email: to be protected. Should never leak to contact.
  6. This script makes sure that in the forward phase, the email that is forwarded to user personal email has the following
  7. envelope and header fields:
  8. Envelope:
  9. mail from: @contact
  10. rcpt to: @personal_email
  11. Header:
  12. From: @contact
  13. To: alias@sl.co # so user knows this email is sent to alias
  14. Reply-to: special@sl.co # magic HERE
  15. And in the reply phase:
  16. Envelope:
  17. mail from: @contact
  18. rcpt to: @contact
  19. Header:
  20. From: alias@sl.co # so for contact the email comes from alias. magic HERE
  21. To: @contact
  22. The special@sl.co allows to hide user personal email when user clicks "Reply" to the forwarded email.
  23. It should contain the following info:
  24. - alias
  25. - @contact
  26. """
  27. import asyncio
  28. import email
  29. import os
  30. import time
  31. import uuid
  32. from email import encoders
  33. from email.message import Message
  34. from email.mime.application import MIMEApplication
  35. from email.mime.multipart import MIMEMultipart
  36. from email.utils import parseaddr, formataddr
  37. from io import BytesIO
  38. from smtplib import SMTP
  39. from typing import List, Tuple
  40. import aiosmtpd
  41. import aiospamc
  42. import arrow
  43. import spf
  44. from aiosmtpd.controller import Controller
  45. from aiosmtpd.smtp import Envelope
  46. from app import pgp_utils, s3
  47. from app.alias_utils import try_auto_create
  48. from app.config import (
  49. EMAIL_DOMAIN,
  50. POSTFIX_SERVER,
  51. URL,
  52. ALIAS_DOMAINS,
  53. POSTFIX_SUBMISSION_TLS,
  54. UNSUBSCRIBER,
  55. LOAD_PGP_EMAIL_HANDLER,
  56. ENFORCE_SPF,
  57. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  58. ALERT_BOUNCE_EMAIL,
  59. ALERT_SPAM_EMAIL,
  60. ALERT_SPF,
  61. POSTFIX_PORT,
  62. SENDER,
  63. SENDER_DIR,
  64. SPAMASSASSIN_HOST,
  65. MAX_SPAM_SCORE,
  66. MAX_REPLY_PHASE_SPAM_SCORE,
  67. )
  68. from app.email_utils import (
  69. send_email,
  70. add_dkim_signature,
  71. add_or_replace_header,
  72. delete_header,
  73. email_belongs_to_alias_domains,
  74. render,
  75. get_orig_message_from_bounce,
  76. delete_all_headers_except,
  77. get_addrs_from_header,
  78. get_spam_info,
  79. get_orig_message_from_spamassassin_report,
  80. parseaddr_unicode,
  81. send_email_with_rate_control,
  82. get_email_domain_part,
  83. copy,
  84. )
  85. from app.extensions import db
  86. from app.greylisting import greylisting_needed
  87. from app.log import LOG
  88. from app.models import (
  89. Alias,
  90. Contact,
  91. EmailLog,
  92. CustomDomain,
  93. User,
  94. RefusedEmail,
  95. Mailbox,
  96. )
  97. from app.pgp_utils import PGPException
  98. from app.utils import random_string
  99. from init_app import load_pgp_public_keys
  100. from server import create_app, create_light_app
  101. _IP_HEADER = "X-SimpleLogin-Client-IP"
  102. _MAILBOX_ID_HEADER = "X-SimpleLogin-Mailbox-ID"
  103. _EMAIL_LOG_ID_HEADER = "X-SimpleLogin-EmailLog-ID"
  104. # fix the database connection leak issue
  105. # use this method instead of create_app
  106. def new_app():
  107. app = create_light_app()
  108. @app.teardown_appcontext
  109. def shutdown_session(response_or_exc):
  110. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  111. db.session.remove()
  112. # dispose the engine too
  113. db.engine.dispose()
  114. return app
  115. def get_or_create_contact(
  116. contact_from_header: str, mail_from: str, alias: Alias
  117. ) -> Contact:
  118. """
  119. contact_from_header is the RFC 2047 format FROM header
  120. """
  121. # contact_from_header can be None, use mail_from in this case instead
  122. contact_from_header = contact_from_header or mail_from
  123. # force convert header to string, sometimes contact_from_header is Header object
  124. contact_from_header = str(contact_from_header)
  125. contact_name, contact_email = parseaddr_unicode(contact_from_header)
  126. if not contact_email:
  127. # From header is wrongly formatted, try with mail_from
  128. LOG.warning("From header is empty, parse mail_from %s %s", mail_from, alias)
  129. contact_name, contact_email = parseaddr_unicode(mail_from)
  130. if not contact_email:
  131. LOG.exception(
  132. "Cannot parse contact from from_header:%s, mail_from:%s",
  133. contact_from_header,
  134. mail_from,
  135. )
  136. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  137. if contact:
  138. if contact.name != contact_name:
  139. LOG.d(
  140. "Update contact %s name %s to %s", contact, contact.name, contact_name,
  141. )
  142. contact.name = contact_name
  143. db.session.commit()
  144. else:
  145. LOG.debug(
  146. "create contact for alias %s and contact %s", alias, contact_from_header,
  147. )
  148. reply_email = generate_reply_email()
  149. contact = Contact.create(
  150. user_id=alias.user_id,
  151. alias_id=alias.id,
  152. website_email=contact_email,
  153. name=contact_name,
  154. reply_email=reply_email,
  155. )
  156. db.session.commit()
  157. return contact
  158. def replace_header_when_forward(msg: Message, alias: Alias, header: str):
  159. """
  160. Replace CC or To header by Reply emails in forward phase
  161. """
  162. addrs = get_addrs_from_header(msg, header)
  163. # Nothing to do
  164. if not addrs:
  165. return
  166. new_addrs: [str] = []
  167. need_replace = False
  168. for addr in addrs:
  169. contact_name, contact_email = parseaddr_unicode(addr)
  170. # no transformation when alias is already in the header
  171. if contact_email == alias.email:
  172. new_addrs.append(addr)
  173. continue
  174. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  175. if contact:
  176. # update the contact name if needed
  177. if contact.name != contact_name:
  178. LOG.d(
  179. "Update contact %s name %s to %s",
  180. contact,
  181. contact.name,
  182. contact_name,
  183. )
  184. contact.name = contact_name
  185. db.session.commit()
  186. else:
  187. LOG.debug(
  188. "create contact for alias %s and email %s, header %s",
  189. alias,
  190. contact_email,
  191. header,
  192. )
  193. reply_email = generate_reply_email()
  194. contact = Contact.create(
  195. user_id=alias.user_id,
  196. alias_id=alias.id,
  197. website_email=contact_email,
  198. name=contact_name,
  199. reply_email=reply_email,
  200. is_cc=header.lower() == "cc",
  201. )
  202. db.session.commit()
  203. new_addrs.append(contact.new_addr())
  204. need_replace = True
  205. if need_replace:
  206. new_header = ",".join(new_addrs)
  207. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  208. add_or_replace_header(msg, header, new_header)
  209. else:
  210. LOG.d("No need to replace %s header", header)
  211. def replace_header_when_reply(msg: Message, alias: Alias, header: str):
  212. """
  213. Replace CC or To Reply emails by original emails
  214. """
  215. addrs = get_addrs_from_header(msg, header)
  216. # Nothing to do
  217. if not addrs:
  218. return
  219. new_addrs: [str] = []
  220. for addr in addrs:
  221. name, reply_email = parseaddr(addr)
  222. # no transformation when alias is already in the header
  223. if reply_email == alias.email:
  224. continue
  225. contact = Contact.get_by(reply_email=reply_email)
  226. if not contact:
  227. LOG.warning(
  228. "%s email in reply phase %s must be reply emails", header, reply_email
  229. )
  230. # still keep this email in header
  231. new_addrs.append(addr)
  232. else:
  233. new_addrs.append(formataddr((contact.name, contact.website_email)))
  234. new_header = ",".join(new_addrs)
  235. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  236. add_or_replace_header(msg, header, new_header)
  237. def replace_str_in_msg(msg: Message, fr: str, to: str):
  238. if msg.get_content_maintype() != "text":
  239. return msg
  240. new_body = msg.get_payload(decode=True).replace(fr.encode(), to.encode())
  241. # If utf-8 decoding fails, do not touch message part
  242. try:
  243. new_body = new_body.decode("utf-8")
  244. except:
  245. return msg
  246. cte = (
  247. msg["Content-Transfer-Encoding"].lower()
  248. if msg["Content-Transfer-Encoding"]
  249. else None
  250. )
  251. subtype = msg.get_content_subtype()
  252. delete_header(msg, "Content-Transfer-Encoding")
  253. delete_header(msg, "Content-Type")
  254. email.contentmanager.set_text_content(msg, new_body, subtype=subtype, cte=cte)
  255. return msg
  256. def generate_reply_email():
  257. # generate a reply_email, make sure it is unique
  258. # not use while loop to avoid infinite loop
  259. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  260. for _ in range(1000):
  261. if not Contact.get_by(reply_email=reply_email):
  262. # found!
  263. break
  264. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  265. return reply_email
  266. def should_append_alias(msg: Message, address: str):
  267. """whether an alias should be appended to TO header in message"""
  268. # # force convert header to string, sometimes addrs is Header object
  269. if msg["To"] and address.lower() in str(msg["To"]).lower():
  270. return False
  271. if msg["Cc"] and address.lower() in str(msg["Cc"]).lower():
  272. return False
  273. return True
  274. _MIME_HEADERS = [
  275. "MIME-Version",
  276. "Content-Type",
  277. "Content-Disposition",
  278. "Content-Transfer-Encoding",
  279. ]
  280. _MIME_HEADERS = [h.lower() for h in _MIME_HEADERS]
  281. def prepare_pgp_message(orig_msg: Message, pgp_fingerprint: str):
  282. msg = MIMEMultipart("encrypted", protocol="application/pgp-encrypted")
  283. # copy all headers from original message except all standard MIME headers
  284. for i in reversed(range(len(orig_msg._headers))):
  285. header_name = orig_msg._headers[i][0].lower()
  286. if header_name.lower() not in _MIME_HEADERS:
  287. msg[header_name] = orig_msg._headers[i][1]
  288. # Delete unnecessary headers in orig_msg except to save space
  289. delete_all_headers_except(
  290. orig_msg, _MIME_HEADERS,
  291. )
  292. first = MIMEApplication(
  293. _subtype="pgp-encrypted", _encoder=encoders.encode_7or8bit, _data=""
  294. )
  295. first.set_payload("Version: 1")
  296. msg.attach(first)
  297. second = MIMEApplication("octet-stream", _encoder=encoders.encode_7or8bit)
  298. second.add_header("Content-Disposition", "inline")
  299. # encrypt original message
  300. encrypted_data = pgp_utils.encrypt_file(
  301. BytesIO(orig_msg.as_bytes()), pgp_fingerprint
  302. )
  303. second.set_payload(encrypted_data)
  304. msg.attach(second)
  305. return msg
  306. async def handle_forward(
  307. envelope, smtp: SMTP, msg: Message, rcpt_to: str
  308. ) -> List[Tuple[bool, str]]:
  309. """return whether an email has been delivered and
  310. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  311. """
  312. address = rcpt_to.lower().strip() # alias@SL
  313. alias = Alias.get_by(email=address)
  314. if not alias:
  315. LOG.d("alias %s not exist. Try to see if it can be created on the fly", address)
  316. alias = try_auto_create(address)
  317. if not alias:
  318. LOG.d("alias %s cannot be created on-the-fly, return 550", address)
  319. return [(False, "550 SL E3 Email not exist")]
  320. contact = get_or_create_contact(msg["From"], envelope.mail_from, alias)
  321. email_log = EmailLog.create(contact_id=contact.id, user_id=contact.user_id)
  322. db.session.commit()
  323. if not alias.enabled:
  324. LOG.d("%s is disabled, do not forward", alias)
  325. email_log.blocked = True
  326. db.session.commit()
  327. # do not return 5** to allow user to receive emails later when alias is enabled
  328. return [(True, "250 Message accepted for delivery")]
  329. user = alias.user
  330. ret = []
  331. mailboxes = alias.mailboxes
  332. # no need to create a copy of message
  333. if len(mailboxes) == 1:
  334. mailbox = mailboxes[0]
  335. ret.append(
  336. await forward_email_to_mailbox(
  337. alias, msg, email_log, contact, envelope, smtp, mailbox, user
  338. )
  339. )
  340. # create a copy of message for each forward
  341. else:
  342. for mailbox in mailboxes:
  343. ret.append(
  344. await forward_email_to_mailbox(
  345. alias, copy(msg), email_log, contact, envelope, smtp, mailbox, user
  346. )
  347. )
  348. return ret
  349. async def forward_email_to_mailbox(
  350. alias,
  351. msg: Message,
  352. email_log: EmailLog,
  353. contact: Contact,
  354. envelope,
  355. smtp: SMTP,
  356. mailbox,
  357. user,
  358. ) -> (bool, str):
  359. LOG.d("Forward %s -> %s -> %s", contact, alias, mailbox)
  360. # sanity check: make sure mailbox is not actually an alias
  361. if get_email_domain_part(alias.email) == get_email_domain_part(mailbox.email):
  362. LOG.exception(
  363. "Mailbox has the same domain as alias. %s -> %s -> %s",
  364. contact,
  365. alias,
  366. mailbox,
  367. )
  368. return False, "550 SL E14"
  369. # Spam check
  370. spam_status = ""
  371. is_spam = False
  372. if SPAMASSASSIN_HOST:
  373. spam_score = await get_spam_score(msg)
  374. LOG.d("%s -> %s spam score %s", contact, alias, spam_score)
  375. email_log.spam_score = spam_score
  376. db.session.commit()
  377. if (user.max_spam_score and spam_score > user.max_spam_score) or (
  378. not user.max_spam_score and spam_score > MAX_SPAM_SCORE
  379. ):
  380. is_spam = True
  381. spam_status = "Spam detected by SpamAssassin server"
  382. else:
  383. is_spam, spam_status = get_spam_info(msg, max_score=user.max_spam_score)
  384. if is_spam:
  385. LOG.warning("Email detected as spam. Alias: %s, from: %s", alias, contact)
  386. email_log.is_spam = True
  387. email_log.spam_status = spam_status
  388. db.session.commit()
  389. handle_spam(contact, alias, msg, user, mailbox, email_log)
  390. return False, "550 SL E1 Email detected as spam"
  391. # create PGP email if needed
  392. if mailbox.pgp_finger_print and user.is_premium() and not alias.disable_pgp:
  393. LOG.d("Encrypt message using mailbox %s", mailbox)
  394. try:
  395. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  396. except PGPException:
  397. LOG.exception(
  398. "Cannot encrypt message %s -> %s. %s %s", contact, alias, mailbox, user
  399. )
  400. # so the client can retry later
  401. return False, "421 SL E12 Retry later"
  402. # add custom header
  403. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  404. # remove reply-to & sender header if present
  405. delete_header(msg, "Reply-To")
  406. delete_header(msg, "Sender")
  407. delete_header(msg, _IP_HEADER)
  408. add_or_replace_header(msg, _MAILBOX_ID_HEADER, str(mailbox.id))
  409. add_or_replace_header(msg, _EMAIL_LOG_ID_HEADER, str(email_log.id))
  410. # change the from header so the sender comes from @SL
  411. # so it can pass DMARC check
  412. # replace the email part in from: header
  413. contact_from_header = msg["From"]
  414. new_from_header = contact.new_addr()
  415. add_or_replace_header(msg, "From", new_from_header)
  416. LOG.d("new_from_header:%s, old header %s", new_from_header, contact_from_header)
  417. # replace CC & To emails by reply-email for all emails that are not alias
  418. replace_header_when_forward(msg, alias, "Cc")
  419. replace_header_when_forward(msg, alias, "To")
  420. # append alias into the TO header if it's not present in To or CC
  421. if should_append_alias(msg, alias.email):
  422. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  423. if msg["To"]:
  424. to_header = msg["To"] + "," + alias.email
  425. else:
  426. to_header = alias.email
  427. add_or_replace_header(msg, "To", to_header.strip())
  428. # add List-Unsubscribe header
  429. if UNSUBSCRIBER:
  430. unsubscribe_link = f"mailto:{UNSUBSCRIBER}?subject={alias.id}="
  431. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  432. else:
  433. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  434. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  435. add_or_replace_header(
  436. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  437. )
  438. add_dkim_signature(msg, EMAIL_DOMAIN)
  439. LOG.d(
  440. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  441. contact.website_email,
  442. mailbox.email,
  443. envelope.mail_options,
  444. envelope.rcpt_options,
  445. )
  446. # smtp.send_message has UnicodeEncodeErroremail issue
  447. # encode message raw directly instead
  448. smtp.sendmail(
  449. contact.reply_email,
  450. mailbox.email,
  451. msg.as_bytes(),
  452. envelope.mail_options,
  453. envelope.rcpt_options,
  454. )
  455. db.session.commit()
  456. return True, "250 Message accepted for delivery"
  457. async def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> (bool, str):
  458. """
  459. return whether an email has been delivered and
  460. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  461. """
  462. reply_email = rcpt_to.lower().strip()
  463. # reply_email must end with EMAIL_DOMAIN
  464. if not reply_email.endswith(EMAIL_DOMAIN):
  465. LOG.warning(f"Reply email {reply_email} has wrong domain")
  466. return False, "550 SL E2"
  467. contact = Contact.get_by(reply_email=reply_email)
  468. if not contact:
  469. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  470. return False, "550 SL E4 Email not exist"
  471. alias = contact.alias
  472. address: str = contact.alias.email
  473. alias_domain = address[address.find("@") + 1 :]
  474. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  475. if not email_belongs_to_alias_domains(alias.email):
  476. if not CustomDomain.get_by(domain=alias_domain):
  477. return False, "550 SL E5"
  478. user = alias.user
  479. mail_from = envelope.mail_from.lower().strip()
  480. # bounce email initiated by Postfix
  481. # can happen in case emails cannot be delivered to user-email
  482. # in this case Postfix will try to send a bounce report to original sender, which is
  483. # the "reply email"
  484. if mail_from == "<>":
  485. LOG.warning(
  486. "Bounce when sending to alias %s from %s, user %s", alias, contact, user,
  487. )
  488. handle_bounce(contact, alias, msg, user)
  489. return False, "550 SL E6"
  490. mailbox = Mailbox.get_by(email=mail_from, user_id=user.id)
  491. if not mailbox or mailbox not in alias.mailboxes:
  492. # only mailbox can send email to the reply-email
  493. handle_unknown_mailbox(envelope, msg, reply_email, user, alias)
  494. return False, "550 SL E7"
  495. if ENFORCE_SPF and mailbox.force_spf:
  496. ip = msg[_IP_HEADER]
  497. if not spf_pass(ip, envelope, mailbox, user, alias, contact.website_email, msg):
  498. # cannot use 4** here as sender will retry. 5** because that generates bounce report
  499. return True, "250 SL E11"
  500. email_log = EmailLog.create(
  501. contact_id=contact.id, is_reply=True, user_id=contact.user_id
  502. )
  503. # Spam check
  504. spam_status = ""
  505. is_spam = False
  506. # do not use user.max_spam_score here
  507. if SPAMASSASSIN_HOST:
  508. spam_score = await get_spam_score(msg)
  509. LOG.d("%s -> %s - spam score %s", alias, contact, spam_score)
  510. email_log.spam_score = spam_score
  511. if spam_score > MAX_REPLY_PHASE_SPAM_SCORE:
  512. is_spam = True
  513. spam_status = "Spam detected by SpamAssassin server"
  514. else:
  515. is_spam, spam_status = get_spam_info(msg, max_score=MAX_REPLY_PHASE_SPAM_SCORE)
  516. if is_spam:
  517. LOG.exception(
  518. "Reply phase - email sent from %s to %s detected as spam", alias, contact
  519. )
  520. email_log.is_spam = True
  521. email_log.spam_status = spam_status
  522. db.session.commit()
  523. handle_spam(contact, alias, msg, user, mailbox, email_log, is_reply=True)
  524. return False, "550 SL E15 Email detected as spam"
  525. delete_header(msg, _IP_HEADER)
  526. delete_header(msg, "DKIM-Signature")
  527. delete_header(msg, "Received")
  528. # make the email comes from alias
  529. from_header = alias.email
  530. # add alias name from alias
  531. if alias.name:
  532. LOG.d("Put alias name in from header")
  533. from_header = formataddr((alias.name, alias.email))
  534. elif alias.custom_domain:
  535. LOG.d("Put domain default alias name in from header")
  536. # add alias name from domain
  537. if alias.custom_domain.name:
  538. from_header = formataddr((alias.custom_domain.name, alias.email))
  539. add_or_replace_header(msg, "From", from_header)
  540. # some email providers like ProtonMail adds automatically the Reply-To field
  541. # make sure to delete it
  542. delete_header(msg, "Reply-To")
  543. # remove sender header if present as this could reveal user real email
  544. delete_header(msg, "Sender")
  545. delete_header(msg, "X-Sender")
  546. replace_header_when_reply(msg, alias, "To")
  547. replace_header_when_reply(msg, alias, "Cc")
  548. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  549. delete_header(msg, "Received-SPF")
  550. LOG.d(
  551. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  552. alias.email,
  553. contact.website_email,
  554. envelope.mail_options,
  555. envelope.rcpt_options,
  556. )
  557. # replace "ra+string@simplelogin.co" by the contact email in the email body
  558. # as this is usually included when replying
  559. if user.replace_reverse_alias:
  560. if msg.is_multipart():
  561. for part in msg.walk():
  562. if part.get_content_maintype() != "text":
  563. continue
  564. part = replace_str_in_msg(part, reply_email, contact.website_email)
  565. else:
  566. msg = replace_str_in_msg(msg, reply_email, contact.website_email)
  567. if alias_domain in ALIAS_DOMAINS:
  568. add_dkim_signature(msg, alias_domain)
  569. # add DKIM-Signature for custom-domain alias
  570. else:
  571. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  572. if custom_domain.dkim_verified:
  573. add_dkim_signature(msg, alias_domain)
  574. # create PGP email if needed
  575. if contact.pgp_finger_print and user.is_premium():
  576. LOG.d("Encrypt message for contact %s", contact)
  577. try:
  578. msg = prepare_pgp_message(msg, contact.pgp_finger_print)
  579. except PGPException:
  580. LOG.exception(
  581. "Cannot encrypt message %s -> %s. %s %s", alias, contact, mailbox, user
  582. )
  583. # to not save the email_log
  584. db.session.rollback()
  585. # return 421 so the client can retry later
  586. return False, "421 SL E13 Retry later"
  587. try:
  588. smtp.sendmail(
  589. alias.email,
  590. contact.website_email,
  591. msg.as_bytes(),
  592. envelope.mail_options,
  593. envelope.rcpt_options,
  594. )
  595. except Exception:
  596. # to not save the email_log
  597. db.session.rollback()
  598. LOG.exception("Cannot send email from %s to %s", alias, contact)
  599. send_email(
  600. mailbox.email,
  601. f"Email cannot be sent to {contact.email} from {alias.email}",
  602. render(
  603. "transactional/reply-error.txt",
  604. user=user,
  605. alias=alias,
  606. contact=contact,
  607. contact_domain=get_email_domain_part(contact.email),
  608. ),
  609. render(
  610. "transactional/reply-error.html",
  611. user=user,
  612. alias=alias,
  613. contact=contact,
  614. contact_domain=get_email_domain_part(contact.email),
  615. ),
  616. )
  617. db.session.commit()
  618. return True, "250 Message accepted for delivery"
  619. def spf_pass(
  620. ip: str,
  621. envelope,
  622. mailbox: Mailbox,
  623. user: User,
  624. alias: Alias,
  625. contact_email: str,
  626. msg: Message,
  627. ) -> bool:
  628. if ip:
  629. LOG.d("Enforce SPF")
  630. try:
  631. r = spf.check2(i=ip, s=envelope.mail_from.lower(), h=None)
  632. except Exception:
  633. LOG.exception("SPF error, mailbox %s, ip %s", mailbox.email, ip)
  634. else:
  635. # TODO: Handle temperr case (e.g. dns timeout)
  636. # only an absolute pass, or no SPF policy at all is 'valid'
  637. if r[0] not in ["pass", "none"]:
  638. LOG.warning(
  639. "SPF fail for mailbox %s, reason %s, failed IP %s",
  640. mailbox.email,
  641. r[0],
  642. ip,
  643. )
  644. send_email_with_rate_control(
  645. user,
  646. ALERT_SPF,
  647. mailbox.email,
  648. f"SimpleLogin Alert: attempt to send emails from your alias {alias.email} from unknown IP Address",
  649. render(
  650. "transactional/spf-fail.txt",
  651. name=user.name,
  652. alias=alias.email,
  653. ip=ip,
  654. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  655. to_email=contact_email,
  656. subject=msg["Subject"],
  657. time=arrow.now(),
  658. ),
  659. render(
  660. "transactional/spf-fail.html",
  661. name=user.name,
  662. alias=alias.email,
  663. ip=ip,
  664. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  665. to_email=contact_email,
  666. subject=msg["Subject"],
  667. time=arrow.now(),
  668. ),
  669. )
  670. return False
  671. else:
  672. LOG.warning(
  673. "Could not find %s header %s -> %s",
  674. _IP_HEADER,
  675. mailbox.email,
  676. contact_email,
  677. )
  678. return True
  679. def handle_unknown_mailbox(envelope, msg, reply_email: str, user: User, alias: Alias):
  680. LOG.warning(
  681. f"Reply email can only be used by mailbox. "
  682. f"Actual mail_from: %s. msg from header: %s, reverse-alias %s, %s %s",
  683. envelope.mail_from,
  684. msg["From"],
  685. reply_email,
  686. alias,
  687. user,
  688. )
  689. send_email_with_rate_control(
  690. user,
  691. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  692. user.email,
  693. f"Reply from your alias {alias.email} only works from your mailbox",
  694. render(
  695. "transactional/reply-must-use-personal-email.txt",
  696. name=user.name,
  697. alias=alias,
  698. sender=envelope.mail_from,
  699. ),
  700. render(
  701. "transactional/reply-must-use-personal-email.html",
  702. name=user.name,
  703. alias=alias,
  704. sender=envelope.mail_from,
  705. ),
  706. )
  707. # Notify sender that they cannot send emails to this address
  708. send_email_with_rate_control(
  709. user,
  710. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  711. envelope.mail_from,
  712. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  713. render(
  714. "transactional/send-from-alias-from-unknown-sender.txt",
  715. sender=envelope.mail_from,
  716. reply_email=reply_email,
  717. ),
  718. render(
  719. "transactional/send-from-alias-from-unknown-sender.html",
  720. sender=envelope.mail_from,
  721. reply_email=reply_email,
  722. ),
  723. )
  724. def handle_bounce(contact: Contact, alias: Alias, msg: Message, user: User):
  725. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  726. # <<< Store the bounced email >>>
  727. # generate a name for the email
  728. random_name = str(uuid.uuid4())
  729. full_report_path = f"refused-emails/full-{random_name}.eml"
  730. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  731. file_path = None
  732. mailbox = alias.mailbox
  733. email_log: EmailLog = None
  734. orig_msg = get_orig_message_from_bounce(msg)
  735. if not orig_msg:
  736. # Some MTA does not return the original message in bounce message
  737. # nothing we can do here
  738. LOG.warning(
  739. "Cannot parse original message from bounce message %s %s %s %s",
  740. alias,
  741. user,
  742. contact,
  743. full_report_path,
  744. )
  745. else:
  746. file_path = f"refused-emails/{random_name}.eml"
  747. s3.upload_email_from_bytesio(
  748. file_path, BytesIO(orig_msg.as_bytes()), random_name
  749. )
  750. # <<< END Store the bounced email >>>
  751. try:
  752. mailbox_id = int(orig_msg[_MAILBOX_ID_HEADER])
  753. except TypeError:
  754. LOG.warning("cannot parse mailbox from %s", orig_msg[_MAILBOX_ID_HEADER])
  755. # use the alias default mailbox
  756. mailbox = alias.mailbox
  757. else:
  758. mailbox = Mailbox.get(mailbox_id)
  759. if not mailbox or mailbox.user_id != user.id:
  760. LOG.exception(
  761. "Tampered message mailbox_id %s, %s, %s, %s %s",
  762. mailbox_id,
  763. user,
  764. alias,
  765. contact,
  766. full_report_path,
  767. )
  768. # use the alias default mailbox
  769. mailbox = alias.mailbox
  770. # try to get the original email_log
  771. try:
  772. email_log_id = int(orig_msg[_EMAIL_LOG_ID_HEADER])
  773. except TypeError:
  774. LOG.warning(
  775. "cannot parse original email log from %s",
  776. orig_msg[_EMAIL_LOG_ID_HEADER],
  777. )
  778. else:
  779. email_log = EmailLog.get(email_log_id)
  780. refused_email = RefusedEmail.create(
  781. path=file_path, full_report_path=full_report_path, user_id=user.id
  782. )
  783. db.session.flush()
  784. if not email_log:
  785. LOG.warning("cannot get the original email_log, create a new one")
  786. email_log: EmailLog = EmailLog.create(
  787. contact_id=contact.id, user_id=contact.user_id
  788. )
  789. email_log.bounced = True
  790. email_log.refused_email_id = refused_email.id
  791. email_log.bounced_mailbox_id = mailbox.id
  792. db.session.commit()
  793. LOG.d("Create refused email %s", refused_email)
  794. refused_email_url = (
  795. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  796. )
  797. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  798. # inform user if this is the first bounced email
  799. if nb_bounced == 1:
  800. LOG.d(
  801. "Inform user %s about bounced email sent by %s to alias %s",
  802. user,
  803. contact.website_email,
  804. alias,
  805. )
  806. send_email_with_rate_control(
  807. user,
  808. ALERT_BOUNCE_EMAIL,
  809. user.email,
  810. f"Email from {contact.website_email} to {alias.email} cannot be delivered to your inbox",
  811. render(
  812. "transactional/bounced-email.txt",
  813. name=user.name,
  814. alias=alias,
  815. website_email=contact.website_email,
  816. disable_alias_link=disable_alias_link,
  817. refused_email_url=refused_email_url,
  818. mailbox_email=mailbox.email,
  819. ),
  820. render(
  821. "transactional/bounced-email.html",
  822. name=user.name,
  823. alias=alias,
  824. website_email=contact.website_email,
  825. disable_alias_link=disable_alias_link,
  826. refused_email_url=refused_email_url,
  827. mailbox_email=mailbox.email,
  828. ),
  829. )
  830. # disable the alias the second time email is bounced
  831. elif nb_bounced >= 2:
  832. if alias.cannot_be_disabled:
  833. LOG.warning("%s cannot be disabled", alias)
  834. else:
  835. LOG.d(
  836. "Bounce happens again with alias %s from %s. Disable alias now ",
  837. alias,
  838. contact.website_email,
  839. )
  840. alias.enabled = False
  841. db.session.commit()
  842. send_email_with_rate_control(
  843. user,
  844. ALERT_BOUNCE_EMAIL,
  845. user.email,
  846. f"Alias {alias.email} has been disabled due to second undelivered email from {contact.website_email}",
  847. render(
  848. "transactional/automatic-disable-alias.txt",
  849. name=user.name,
  850. alias=alias,
  851. website_email=contact.website_email,
  852. refused_email_url=refused_email_url,
  853. mailbox_email=mailbox.email,
  854. ),
  855. render(
  856. "transactional/automatic-disable-alias.html",
  857. name=user.name,
  858. alias=alias,
  859. website_email=contact.website_email,
  860. refused_email_url=refused_email_url,
  861. mailbox_email=mailbox.email,
  862. ),
  863. )
  864. def handle_spam(
  865. contact: Contact,
  866. alias: Alias,
  867. msg: Message,
  868. user: User,
  869. mailbox: Mailbox,
  870. email_log: EmailLog,
  871. is_reply=False, # whether the email is in forward or reply phase
  872. ):
  873. # Store the report & original email
  874. orig_msg = get_orig_message_from_spamassassin_report(msg)
  875. # generate a name for the email
  876. random_name = str(uuid.uuid4())
  877. full_report_path = f"spams/full-{random_name}.eml"
  878. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  879. file_path = None
  880. if orig_msg:
  881. file_path = f"spams/{random_name}.eml"
  882. s3.upload_email_from_bytesio(
  883. file_path, BytesIO(orig_msg.as_bytes()), random_name
  884. )
  885. refused_email = RefusedEmail.create(
  886. path=file_path, full_report_path=full_report_path, user_id=user.id
  887. )
  888. db.session.flush()
  889. email_log.refused_email_id = refused_email.id
  890. db.session.commit()
  891. LOG.d("Create spam email %s", refused_email)
  892. refused_email_url = (
  893. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  894. )
  895. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  896. if is_reply:
  897. LOG.d(
  898. "Inform %s (%s) about spam email sent from alias %s to %s",
  899. mailbox,
  900. user,
  901. alias,
  902. contact,
  903. )
  904. send_email_with_rate_control(
  905. user,
  906. ALERT_SPAM_EMAIL,
  907. mailbox.email,
  908. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  909. render(
  910. "transactional/spam-email-reply-phase.txt",
  911. name=user.name,
  912. alias=alias,
  913. website_email=contact.website_email,
  914. disable_alias_link=disable_alias_link,
  915. refused_email_url=refused_email_url,
  916. ),
  917. render(
  918. "transactional/spam-email-reply-phase.html",
  919. name=user.name,
  920. alias=alias,
  921. website_email=contact.website_email,
  922. disable_alias_link=disable_alias_link,
  923. refused_email_url=refused_email_url,
  924. ),
  925. )
  926. else:
  927. # inform user
  928. LOG.d(
  929. "Inform %s (%s) about spam email sent by %s to alias %s",
  930. mailbox,
  931. user,
  932. contact,
  933. alias,
  934. )
  935. send_email_with_rate_control(
  936. user,
  937. ALERT_SPAM_EMAIL,
  938. mailbox.email,
  939. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  940. render(
  941. "transactional/spam-email.txt",
  942. name=user.name,
  943. alias=alias,
  944. website_email=contact.website_email,
  945. disable_alias_link=disable_alias_link,
  946. refused_email_url=refused_email_url,
  947. ),
  948. render(
  949. "transactional/spam-email.html",
  950. name=user.name,
  951. alias=alias,
  952. website_email=contact.website_email,
  953. disable_alias_link=disable_alias_link,
  954. refused_email_url=refused_email_url,
  955. ),
  956. )
  957. def handle_unsubscribe(envelope: Envelope):
  958. msg = email.message_from_bytes(envelope.original_content)
  959. # format: alias_id:
  960. subject = msg["Subject"]
  961. try:
  962. # subject has the format {alias.id}=
  963. if subject.endswith("="):
  964. alias_id = int(subject[:-1])
  965. # some email providers might strip off the = suffix
  966. else:
  967. alias_id = int(subject)
  968. alias = Alias.get(alias_id)
  969. except Exception:
  970. LOG.warning("Cannot parse alias from subject %s", msg["Subject"])
  971. return "550 SL E8 Wrongly formatted subject"
  972. if not alias:
  973. LOG.warning("No such alias %s", alias_id)
  974. return "550 SL E9 Email not exist"
  975. # This sender cannot unsubscribe
  976. mail_from = envelope.mail_from.lower().strip()
  977. mailbox = Mailbox.get_by(user_id=alias.user_id, email=mail_from)
  978. if not mailbox or mailbox not in alias.mailboxes:
  979. LOG.d("%s cannot disable alias %s", envelope.mail_from, alias)
  980. return "550 SL E10 unauthorized"
  981. # Sender is owner of this alias
  982. alias.enabled = False
  983. db.session.commit()
  984. user = alias.user
  985. enable_alias_url = URL + f"/dashboard/?highlight_alias_id={alias.id}"
  986. for mailbox in alias.mailboxes:
  987. send_email(
  988. mailbox.email,
  989. f"Alias {alias.email} has been disabled successfully",
  990. render(
  991. "transactional/unsubscribe-disable-alias.txt",
  992. user=user,
  993. alias=alias.email,
  994. enable_alias_url=enable_alias_url,
  995. ),
  996. render(
  997. "transactional/unsubscribe-disable-alias.html",
  998. user=user,
  999. alias=alias.email,
  1000. enable_alias_url=enable_alias_url,
  1001. ),
  1002. )
  1003. return "250 Unsubscribe request accepted"
  1004. def handle_sender_email(envelope: Envelope):
  1005. filename = (
  1006. arrow.now().format("YYYY-MM-DD_HH-mm-ss") + "_" + random_string(10) + ".eml"
  1007. )
  1008. filepath = os.path.join(SENDER_DIR, filename)
  1009. with open(filepath, "wb") as f:
  1010. f.write(envelope.original_content)
  1011. LOG.d("Write email to sender at %s", filepath)
  1012. msg = email.message_from_bytes(envelope.original_content)
  1013. orig = get_orig_message_from_bounce(msg)
  1014. if orig:
  1015. LOG.warning(
  1016. "Original message %s -> %s saved at %s", orig["From"], orig["To"], filepath
  1017. )
  1018. return "250 email to sender accepted"
  1019. async def handle(envelope: Envelope, smtp: SMTP) -> str:
  1020. """Return SMTP status"""
  1021. # unsubscribe request
  1022. if UNSUBSCRIBER and envelope.rcpt_tos == [UNSUBSCRIBER]:
  1023. LOG.d("Handle unsubscribe request from %s", envelope.mail_from)
  1024. return handle_unsubscribe(envelope)
  1025. # emails sent to sender. Probably bounce emails
  1026. if SENDER and envelope.rcpt_tos == [SENDER]:
  1027. LOG.d("Handle email sent to sender from %s", envelope.mail_from)
  1028. return handle_sender_email(envelope)
  1029. # Whether it's necessary to apply greylisting
  1030. if greylisting_needed(envelope.mail_from, envelope.rcpt_tos):
  1031. LOG.warning(
  1032. "Grey listing applied for %s %s", envelope.mail_from, envelope.rcpt_tos
  1033. )
  1034. return "421 SL Retry later"
  1035. # result of all deliveries
  1036. # each element is a couple of whether the delivery is successful and the smtp status
  1037. res: [(bool, str)] = []
  1038. for rcpt_to in envelope.rcpt_tos:
  1039. msg = email.message_from_bytes(envelope.original_content)
  1040. # Reply case
  1041. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  1042. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  1043. LOG.debug(
  1044. ">>> Reply phase %s(%s) -> %s", envelope.mail_from, msg["From"], rcpt_to
  1045. )
  1046. is_delivered, smtp_status = await handle_reply(envelope, smtp, msg, rcpt_to)
  1047. res.append((is_delivered, smtp_status))
  1048. else: # Forward case
  1049. LOG.debug(
  1050. ">>> Forward phase %s(%s) -> %s",
  1051. envelope.mail_from,
  1052. msg["From"],
  1053. rcpt_to,
  1054. )
  1055. for is_delivered, smtp_status in await handle_forward(
  1056. envelope, smtp, msg, rcpt_to
  1057. ):
  1058. res.append((is_delivered, smtp_status))
  1059. for (is_success, smtp_status) in res:
  1060. # Consider all deliveries successful if 1 delivery is successful
  1061. if is_success:
  1062. return smtp_status
  1063. # Failed delivery for all, return the first failure
  1064. return res[0][1]
  1065. async def get_spam_score(message: Message) -> float:
  1066. sa_input = message.as_bytes()
  1067. # Spamassassin requires to have an ending linebreak
  1068. if not sa_input.endswith(b"\n"):
  1069. LOG.d("add linebreak to spamassassin input")
  1070. sa_input += b"\n"
  1071. try:
  1072. # wait for at max 300s which is the default spamd timeout-child
  1073. response = await asyncio.wait_for(
  1074. aiospamc.check(sa_input, host=SPAMASSASSIN_HOST), timeout=300
  1075. )
  1076. return response.headers["Spam"].score
  1077. except asyncio.TimeoutError:
  1078. LOG.exception("SpamAssassin timeout")
  1079. # return a negative score so the message is always considered as ham
  1080. return -999
  1081. except Exception:
  1082. LOG.exception("SpamAssassin exception")
  1083. return -999
  1084. class MailHandler:
  1085. def __init__(self, lock):
  1086. self.lock = lock
  1087. async def handle_DATA(self, server, session, envelope: Envelope):
  1088. try:
  1089. ret = await self._handle(envelope)
  1090. return ret
  1091. except Exception:
  1092. LOG.exception(
  1093. "email handling fail %s -> %s", envelope.mail_from, envelope.rcpt_tos,
  1094. )
  1095. return "421 SL Retry later"
  1096. async def _handle(self, envelope: Envelope):
  1097. async with self.lock:
  1098. start = time.time()
  1099. LOG.info(
  1100. "===>> New message, mail from %s, rctp tos %s ",
  1101. envelope.mail_from,
  1102. envelope.rcpt_tos,
  1103. )
  1104. if POSTFIX_SUBMISSION_TLS:
  1105. smtp = SMTP(POSTFIX_SERVER, 587)
  1106. smtp.starttls()
  1107. else:
  1108. smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25)
  1109. app = new_app()
  1110. with app.app_context():
  1111. ret = await handle(envelope, smtp)
  1112. LOG.info("takes %s seconds <<===", time.time() - start)
  1113. return ret
  1114. if __name__ == "__main__":
  1115. if LOAD_PGP_EMAIL_HANDLER:
  1116. LOG.warning("LOAD PGP keys")
  1117. app = create_app()
  1118. with app.app_context():
  1119. load_pgp_public_keys()
  1120. loop = asyncio.new_event_loop()
  1121. asyncio.set_event_loop(loop)
  1122. lock = asyncio.Lock()
  1123. handler = MailHandler(lock)
  1124. def factory():
  1125. return aiosmtpd.smtp.SMTP(handler, enable_SMTPUTF8=True)
  1126. server = loop.run_until_complete(
  1127. loop.create_server(factory, host="0.0.0.0", port=20381)
  1128. )
  1129. try:
  1130. loop.run_forever()
  1131. except KeyboardInterrupt:
  1132. pass
  1133. # Close the server
  1134. LOG.info("Close SMTP server")
  1135. server.close()
  1136. loop.run_until_complete(server.wait_closed())
  1137. loop.close()