email_handler.py 31 KB

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