email_handler.py 29 KB

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