email_handler.py 33 KB

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