email_handler.py 35 KB

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