email_handler.py 29 KB

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