email_handler.py 30 KB

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