email_handler.py 30 KB

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