email_handler.py 35 KB

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