email_handler.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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. spam_check = True
  295. # create PGP email if needed
  296. if mailbox.pgp_finger_print and user.is_premium():
  297. LOG.d("Encrypt message using mailbox %s", mailbox)
  298. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  299. # no need to spam check for encrypted message
  300. spam_check = False
  301. if spam_check:
  302. is_spam, spam_status = get_spam_info(msg)
  303. if is_spam:
  304. LOG.warning("Email detected as spam. Alias: %s, from: %s", alias, contact)
  305. email_log.is_spam = True
  306. email_log.spam_status = spam_status
  307. handle_spam(contact, alias, msg, user, mailbox_email, email_log)
  308. return False, "550 SL E1"
  309. # add custom header
  310. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  311. # remove reply-to & sender header if present
  312. delete_header(msg, "Reply-To")
  313. delete_header(msg, "Sender")
  314. delete_header(msg, _IP_HEADER)
  315. # change the from header so the sender comes from @SL
  316. # so it can pass DMARC check
  317. # replace the email part in from: header
  318. contact_from_header = msg["From"]
  319. new_from_header = contact.new_addr()
  320. add_or_replace_header(msg, "From", new_from_header)
  321. LOG.d("new_from_header:%s, old header %s", new_from_header, contact_from_header)
  322. # replace CC & To emails by reply-email for all emails that are not alias
  323. replace_header_when_forward(msg, alias, "Cc")
  324. replace_header_when_forward(msg, alias, "To")
  325. # append alias into the TO header if it's not present in To or CC
  326. if should_append_alias(msg, alias.email):
  327. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  328. if msg["To"]:
  329. to_header = msg["To"] + "," + alias.email
  330. else:
  331. to_header = alias.email
  332. add_or_replace_header(msg, "To", to_header.strip())
  333. # add List-Unsubscribe header
  334. if UNSUBSCRIBER:
  335. unsubscribe_link = f"mailto:{UNSUBSCRIBER}?subject={alias.id}="
  336. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  337. else:
  338. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  339. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  340. add_or_replace_header(
  341. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  342. )
  343. add_dkim_signature(msg, EMAIL_DOMAIN)
  344. LOG.d(
  345. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  346. contact.website_email,
  347. mailbox_email,
  348. envelope.mail_options,
  349. envelope.rcpt_options,
  350. )
  351. # smtp.send_message has UnicodeEncodeErroremail issue
  352. # encode message raw directly instead
  353. smtp.sendmail(
  354. contact.reply_email,
  355. mailbox_email,
  356. msg.as_bytes(),
  357. envelope.mail_options,
  358. envelope.rcpt_options,
  359. )
  360. db.session.commit()
  361. return True, "250 Message accepted for delivery"
  362. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> (bool, str):
  363. """
  364. return whether an email has been delivered and
  365. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  366. """
  367. reply_email = rcpt_to.lower()
  368. # reply_email must end with EMAIL_DOMAIN
  369. if not reply_email.endswith(EMAIL_DOMAIN):
  370. LOG.warning(f"Reply email {reply_email} has wrong domain")
  371. return False, "550 SL E2"
  372. contact = Contact.get_by(reply_email=reply_email)
  373. if not contact:
  374. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  375. return False, "550 SL E4"
  376. alias = contact.alias
  377. address: str = contact.alias.email
  378. alias_domain = address[address.find("@") + 1 :]
  379. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  380. if not email_belongs_to_alias_domains(alias.email):
  381. if not CustomDomain.get_by(domain=alias_domain):
  382. return False, "550 SL E5"
  383. user = alias.user
  384. mailbox_email = alias.mailbox_email()
  385. # bounce email initiated by Postfix
  386. # can happen in case emails cannot be delivered to user-email
  387. # in this case Postfix will try to send a bounce report to original sender, which is
  388. # the "reply email"
  389. if envelope.mail_from == "<>":
  390. LOG.warning(
  391. "Bounce when sending to alias %s from %s, user %s",
  392. alias,
  393. contact.website_email,
  394. alias.user,
  395. )
  396. handle_bounce(contact, alias, msg, user, mailbox_email)
  397. return False, "550 SL E6"
  398. mailbox: Mailbox = Mailbox.get_by(email=mailbox_email)
  399. if ENFORCE_SPF and mailbox.force_spf:
  400. ip = msg[_IP_HEADER]
  401. if not spf_pass(ip, envelope, mailbox, user, alias, contact.website_email, msg):
  402. # cannot use 4** here as sender will retry. 5** because that generates bounce report
  403. return True, "250 SL E11"
  404. delete_header(msg, _IP_HEADER)
  405. # only mailbox can send email to the reply-email
  406. if envelope.mail_from.lower() != mailbox_email.lower():
  407. handle_unknown_mailbox(envelope, msg, mailbox, reply_email, user, alias)
  408. return False, "550 SL E7"
  409. delete_header(msg, "DKIM-Signature")
  410. delete_header(msg, "Received")
  411. # make the email comes from alias
  412. from_header = alias.email
  413. # add alias name from alias
  414. if alias.name:
  415. LOG.d("Put alias name in from header")
  416. from_header = formataddr((alias.name, alias.email))
  417. elif alias.custom_domain:
  418. LOG.d("Put domain default alias name in from header")
  419. # add alias name from domain
  420. if alias.custom_domain.name:
  421. from_header = formataddr((alias.custom_domain.name, alias.email))
  422. add_or_replace_header(msg, "From", from_header)
  423. # some email providers like ProtonMail adds automatically the Reply-To field
  424. # make sure to delete it
  425. delete_header(msg, "Reply-To")
  426. # remove sender header if present as this could reveal user real email
  427. delete_header(msg, "Sender")
  428. delete_header(msg, "X-Sender")
  429. replace_header_when_reply(msg, alias, "To")
  430. replace_header_when_reply(msg, alias, "Cc")
  431. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  432. delete_header(msg, "Received-SPF")
  433. LOG.d(
  434. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  435. alias.email,
  436. contact.website_email,
  437. envelope.mail_options,
  438. envelope.rcpt_options,
  439. )
  440. if alias_domain in ALIAS_DOMAINS:
  441. add_dkim_signature(msg, alias_domain)
  442. # add DKIM-Signature for custom-domain alias
  443. else:
  444. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  445. if custom_domain.dkim_verified:
  446. add_dkim_signature(msg, alias_domain)
  447. smtp.sendmail(
  448. alias.email,
  449. contact.website_email,
  450. msg.as_bytes(),
  451. envelope.mail_options,
  452. envelope.rcpt_options,
  453. )
  454. EmailLog.create(contact_id=contact.id, is_reply=True, user_id=contact.user_id)
  455. db.session.commit()
  456. return True, "250 Message accepted for delivery"
  457. def spf_pass(
  458. ip: str,
  459. envelope,
  460. mailbox: Mailbox,
  461. user: User,
  462. alias: Alias,
  463. contact_email: str,
  464. msg: Message,
  465. ) -> bool:
  466. if ip:
  467. LOG.d("Enforce SPF")
  468. try:
  469. r = spf.check2(i=ip, s=envelope.mail_from.lower(), h=None)
  470. except Exception:
  471. LOG.error("SPF error, mailbox %s, ip %s", mailbox.email, ip)
  472. else:
  473. # TODO: Handle temperr case (e.g. dns timeout)
  474. # only an absolute pass, or no SPF policy at all is 'valid'
  475. if r[0] not in ["pass", "none"]:
  476. LOG.error(
  477. "SPF fail for mailbox %s, reason %s, failed IP %s",
  478. mailbox.email,
  479. r[0],
  480. ip,
  481. )
  482. send_email_with_rate_control(
  483. user,
  484. ALERT_SPF,
  485. mailbox.email,
  486. f"SimpleLogin Alert: attempt to send emails from your alias {alias.email} from unknown IP Address",
  487. render(
  488. "transactional/spf-fail.txt",
  489. name=user.name,
  490. alias=alias.email,
  491. ip=ip,
  492. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  493. to_email=contact_email,
  494. subject=msg["Subject"],
  495. time=arrow.now(),
  496. ),
  497. render(
  498. "transactional/spf-fail.html",
  499. name=user.name,
  500. alias=alias.email,
  501. ip=ip,
  502. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  503. to_email=contact_email,
  504. subject=msg["Subject"],
  505. time=arrow.now(),
  506. ),
  507. )
  508. return False
  509. else:
  510. LOG.warning(
  511. "Could not find %s header %s -> %s",
  512. _IP_HEADER,
  513. mailbox.email,
  514. contact_email,
  515. )
  516. return True
  517. def handle_unknown_mailbox(
  518. envelope, msg, mailbox: Mailbox, reply_email: str, user: User, alias: Alias
  519. ):
  520. LOG.warning(
  521. f"Reply email can only be used by mailbox. "
  522. f"Actual mail_from: %s. msg from header: %s, Mailbox %s. reply_email %s",
  523. envelope.mail_from,
  524. msg["From"],
  525. mailbox.email,
  526. reply_email,
  527. )
  528. send_email_with_rate_control(
  529. user,
  530. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  531. mailbox.email,
  532. f"Reply from your alias {alias.email} only works from your mailbox",
  533. render(
  534. "transactional/reply-must-use-personal-email.txt",
  535. name=user.name,
  536. alias=alias.email,
  537. sender=envelope.mail_from,
  538. mailbox_email=mailbox.email,
  539. ),
  540. render(
  541. "transactional/reply-must-use-personal-email.html",
  542. name=user.name,
  543. alias=alias.email,
  544. sender=envelope.mail_from,
  545. mailbox_email=mailbox.email,
  546. ),
  547. )
  548. # Notify sender that they cannot send emails to this address
  549. send_email_with_rate_control(
  550. user,
  551. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  552. envelope.mail_from,
  553. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  554. render(
  555. "transactional/send-from-alias-from-unknown-sender.txt",
  556. sender=envelope.mail_from,
  557. reply_email=reply_email,
  558. ),
  559. render(
  560. "transactional/send-from-alias-from-unknown-sender.html",
  561. sender=envelope.mail_from,
  562. reply_email=reply_email,
  563. ),
  564. )
  565. def handle_bounce(
  566. contact: Contact, alias: Alias, msg: Message, user: User, mailbox_email: str
  567. ):
  568. address = alias.email
  569. email_log: EmailLog = EmailLog.create(
  570. contact_id=contact.id, bounced=True, user_id=contact.user_id
  571. )
  572. db.session.commit()
  573. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  574. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  575. # Store the bounced email
  576. orig_msg = get_orig_message_from_bounce(msg)
  577. # generate a name for the email
  578. random_name = str(uuid.uuid4())
  579. full_report_path = f"refused-emails/full-{random_name}.eml"
  580. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  581. file_path = None
  582. if orig_msg:
  583. file_path = f"refused-emails/{random_name}.eml"
  584. s3.upload_email_from_bytesio(
  585. file_path, BytesIO(orig_msg.as_bytes()), random_name
  586. )
  587. refused_email = RefusedEmail.create(
  588. path=file_path, full_report_path=full_report_path, user_id=user.id
  589. )
  590. db.session.flush()
  591. email_log.refused_email_id = refused_email.id
  592. db.session.commit()
  593. LOG.d("Create refused email %s", refused_email)
  594. refused_email_url = (
  595. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  596. )
  597. # inform user if this is the first bounced email
  598. if nb_bounced == 1:
  599. LOG.d(
  600. "Inform user %s about bounced email sent by %s to alias %s",
  601. user,
  602. contact.website_email,
  603. address,
  604. )
  605. send_email_with_rate_control(
  606. user,
  607. ALERT_BOUNCE_EMAIL,
  608. # use user mail here as only user is authenticated to see the refused email
  609. user.email,
  610. f"Email from {contact.website_email} to {address} cannot be delivered to your inbox",
  611. render(
  612. "transactional/bounced-email.txt",
  613. name=user.name,
  614. alias=alias,
  615. website_email=contact.website_email,
  616. disable_alias_link=disable_alias_link,
  617. refused_email_url=refused_email_url,
  618. mailbox_email=mailbox_email,
  619. ),
  620. render(
  621. "transactional/bounced-email.html",
  622. name=user.name,
  623. alias=alias,
  624. website_email=contact.website_email,
  625. disable_alias_link=disable_alias_link,
  626. refused_email_url=refused_email_url,
  627. mailbox_email=mailbox_email,
  628. ),
  629. # cannot include bounce email as it can contain spammy text
  630. # bounced_email=msg,
  631. )
  632. # disable the alias the second time email is bounced
  633. elif nb_bounced >= 2:
  634. LOG.d(
  635. "Bounce happens again with alias %s from %s. Disable alias now ",
  636. address,
  637. contact.website_email,
  638. )
  639. alias.enabled = False
  640. db.session.commit()
  641. send_email_with_rate_control(
  642. user,
  643. ALERT_BOUNCE_EMAIL,
  644. # use user mail here as only user is authenticated to see the refused email
  645. user.email,
  646. f"Alias {address} has been disabled due to second undelivered email from {contact.website_email}",
  647. render(
  648. "transactional/automatic-disable-alias.txt",
  649. name=user.name,
  650. alias=alias,
  651. website_email=contact.website_email,
  652. refused_email_url=refused_email_url,
  653. mailbox_email=mailbox_email,
  654. ),
  655. render(
  656. "transactional/automatic-disable-alias.html",
  657. name=user.name,
  658. alias=alias,
  659. website_email=contact.website_email,
  660. refused_email_url=refused_email_url,
  661. mailbox_email=mailbox_email,
  662. ),
  663. # cannot include bounce email as it can contain spammy text
  664. # bounced_email=msg,
  665. )
  666. def handle_spam(
  667. contact: Contact,
  668. alias: Alias,
  669. msg: Message,
  670. user: User,
  671. mailbox_email: str,
  672. email_log: EmailLog,
  673. ):
  674. # Store the report & original email
  675. orig_msg = get_orig_message_from_spamassassin_report(msg)
  676. # generate a name for the email
  677. random_name = str(uuid.uuid4())
  678. full_report_path = f"spams/full-{random_name}.eml"
  679. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  680. file_path = None
  681. if orig_msg:
  682. file_path = f"spams/{random_name}.eml"
  683. s3.upload_email_from_bytesio(
  684. file_path, BytesIO(orig_msg.as_bytes()), random_name
  685. )
  686. refused_email = RefusedEmail.create(
  687. path=file_path, full_report_path=full_report_path, user_id=user.id
  688. )
  689. db.session.flush()
  690. email_log.refused_email_id = refused_email.id
  691. db.session.commit()
  692. LOG.d("Create spam email %s", refused_email)
  693. refused_email_url = (
  694. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  695. )
  696. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  697. # inform user
  698. LOG.d(
  699. "Inform user %s about spam email sent by %s to alias %s",
  700. user,
  701. contact.website_email,
  702. alias.email,
  703. )
  704. send_email_with_rate_control(
  705. user,
  706. ALERT_SPAM_EMAIL,
  707. mailbox_email,
  708. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  709. render(
  710. "transactional/spam-email.txt",
  711. name=user.name,
  712. alias=alias,
  713. website_email=contact.website_email,
  714. disable_alias_link=disable_alias_link,
  715. refused_email_url=refused_email_url,
  716. ),
  717. render(
  718. "transactional/spam-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. ),
  725. )
  726. def handle_unsubscribe(envelope: Envelope):
  727. msg = email.message_from_bytes(envelope.original_content)
  728. # format: alias_id:
  729. subject = msg["Subject"]
  730. try:
  731. # subject has the format {alias.id}=
  732. if subject.endswith("="):
  733. alias_id = int(subject[:-1])
  734. # some email providers might strip off the = suffix
  735. else:
  736. alias_id = int(subject)
  737. alias = Alias.get(alias_id)
  738. except Exception:
  739. LOG.warning("Cannot parse alias from subject %s", msg["Subject"])
  740. return "550 SL E8"
  741. if not alias:
  742. LOG.warning("No such alias %s", alias_id)
  743. return "550 SL E9"
  744. # This sender cannot unsubscribe
  745. if alias.mailbox_email() != envelope.mail_from:
  746. LOG.d("%s cannot disable alias %s", envelope.mail_from, alias)
  747. return "550 SL E10"
  748. # Sender is owner of this alias
  749. alias.enabled = False
  750. db.session.commit()
  751. user = alias.user
  752. enable_alias_url = URL + f"/dashboard/?highlight_alias_id={alias.id}"
  753. send_email(
  754. envelope.mail_from,
  755. f"Alias {alias.email} has been disabled successfully",
  756. render(
  757. "transactional/unsubscribe-disable-alias.txt",
  758. user=user,
  759. alias=alias.email,
  760. enable_alias_url=enable_alias_url,
  761. ),
  762. render(
  763. "transactional/unsubscribe-disable-alias.html",
  764. user=user,
  765. alias=alias.email,
  766. enable_alias_url=enable_alias_url,
  767. ),
  768. )
  769. return "250 Unsubscribe request accepted"
  770. def handle(envelope: Envelope, smtp: SMTP) -> str:
  771. """Return SMTP status"""
  772. # unsubscribe request
  773. if UNSUBSCRIBER and envelope.rcpt_tos == [UNSUBSCRIBER]:
  774. LOG.d("Handle unsubscribe request from %s", envelope.mail_from)
  775. return handle_unsubscribe(envelope)
  776. # Whether it's necessary to apply greylisting
  777. if greylisting_needed(envelope.mail_from, envelope.rcpt_tos):
  778. LOG.warning(
  779. "Grey listing applied for %s %s", envelope.mail_from, envelope.rcpt_tos
  780. )
  781. return "421 SL Retry later"
  782. # result of all deliveries
  783. # each element is a couple of whether the delivery is successful and the smtp status
  784. res: [(bool, str)] = []
  785. for rcpt_to in envelope.rcpt_tos:
  786. msg = email.message_from_bytes(envelope.original_content)
  787. # Reply case
  788. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  789. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  790. LOG.debug(">>> Reply phase %s -> %s", envelope.mail_from, rcpt_to)
  791. is_delivered, smtp_status = handle_reply(envelope, smtp, msg, rcpt_to)
  792. res.append((is_delivered, smtp_status))
  793. else: # Forward case
  794. LOG.debug(">>> Forward phase %s -> %s", envelope.mail_from, rcpt_to)
  795. is_delivered, smtp_status = handle_forward(envelope, smtp, msg, rcpt_to)
  796. res.append((is_delivered, smtp_status))
  797. # special handling for self-forwarding
  798. # just consider success delivery in this case
  799. if len(res) == 1 and res[0][1] == _SELF_FORWARDING_STATUS:
  800. LOG.d("Self-forwarding, ignore")
  801. return "250 SL OK"
  802. for (is_success, smtp_status) in res:
  803. # Consider all deliveries successful if 1 delivery is successful
  804. if is_success:
  805. return smtp_status
  806. # Failed delivery for all, return the first failure
  807. return res[0][1]
  808. class MailHandler:
  809. async def handle_DATA(self, server, session, envelope: Envelope):
  810. LOG.debug(
  811. "===>> New message, mail from %s, rctp tos %s ",
  812. envelope.mail_from,
  813. envelope.rcpt_tos,
  814. )
  815. if POSTFIX_SUBMISSION_TLS:
  816. smtp = SMTP(POSTFIX_SERVER, 587)
  817. smtp.starttls()
  818. else:
  819. smtp = SMTP(POSTFIX_SERVER, 25)
  820. app = new_app()
  821. with app.app_context():
  822. return handle(envelope, smtp)
  823. if __name__ == "__main__":
  824. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  825. controller.start()
  826. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  827. if LOAD_PGP_EMAIL_HANDLER:
  828. LOG.warning("LOAD PGP keys")
  829. app = create_app()
  830. with app.app_context():
  831. load_pgp_public_keys(app)
  832. while True:
  833. time.sleep(2)