email_handler.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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 os
  29. import time
  30. import uuid
  31. from email import encoders
  32. from email.message import Message
  33. from email.mime.application import MIMEApplication
  34. from email.mime.multipart import MIMEMultipart
  35. from email.utils import parseaddr, formataddr
  36. from io import BytesIO
  37. from smtplib import SMTP
  38. from typing import List, Tuple
  39. import arrow
  40. import spf
  41. from aiosmtpd.controller import Controller
  42. from aiosmtpd.smtp import Envelope
  43. from app import pgp_utils, s3
  44. from app.alias_utils import try_auto_create
  45. from app.config import (
  46. EMAIL_DOMAIN,
  47. POSTFIX_SERVER,
  48. URL,
  49. ALIAS_DOMAINS,
  50. POSTFIX_SUBMISSION_TLS,
  51. UNSUBSCRIBER,
  52. LOAD_PGP_EMAIL_HANDLER,
  53. ENFORCE_SPF,
  54. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  55. ALERT_BOUNCE_EMAIL,
  56. ALERT_SPAM_EMAIL,
  57. ALERT_SPF,
  58. POSTFIX_PORT,
  59. )
  60. from app.email_utils import (
  61. send_email,
  62. add_dkim_signature,
  63. add_or_replace_header,
  64. delete_header,
  65. email_belongs_to_alias_domains,
  66. render,
  67. get_orig_message_from_bounce,
  68. delete_all_headers_except,
  69. get_addrs_from_header,
  70. get_spam_info,
  71. get_orig_message_from_spamassassin_report,
  72. parseaddr_unicode,
  73. send_email_with_rate_control,
  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. if msg["To"] and address.lower() in msg["To"].lower():
  258. return False
  259. if msg["Cc"] and address.lower() in msg["Cc"].lower():
  260. return False
  261. return True
  262. _MIME_HEADERS = [
  263. "MIME-Version",
  264. "Content-Type",
  265. "Content-Disposition",
  266. "Content-Transfer-Encoding",
  267. ]
  268. _MIME_HEADERS = [h.lower() for h in _MIME_HEADERS]
  269. def prepare_pgp_message(orig_msg: Message, pgp_fingerprint: str):
  270. msg = MIMEMultipart("encrypted", protocol="application/pgp-encrypted")
  271. # copy all headers from original message except all standard MIME headers
  272. for i in reversed(range(len(orig_msg._headers))):
  273. header_name = orig_msg._headers[i][0].lower()
  274. if header_name.lower() not in _MIME_HEADERS:
  275. msg[header_name] = orig_msg._headers[i][1]
  276. # Delete unnecessary headers in orig_msg except to save space
  277. delete_all_headers_except(
  278. orig_msg, _MIME_HEADERS,
  279. )
  280. first = MIMEApplication(
  281. _subtype="pgp-encrypted", _encoder=encoders.encode_7or8bit, _data=""
  282. )
  283. first.set_payload("Version: 1")
  284. msg.attach(first)
  285. second = MIMEApplication("octet-stream", _encoder=encoders.encode_7or8bit)
  286. second.add_header("Content-Disposition", "inline")
  287. # encrypt original message
  288. encrypted_data = pgp_utils.encrypt_file(
  289. BytesIO(orig_msg.as_bytes()), pgp_fingerprint
  290. )
  291. second.set_payload(encrypted_data)
  292. msg.attach(second)
  293. return msg
  294. def handle_forward(
  295. envelope, smtp: SMTP, msg: Message, rcpt_to: str
  296. ) -> List[Tuple[bool, str]]:
  297. """return whether an email has been delivered and
  298. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  299. """
  300. address = rcpt_to.lower().strip() # alias@SL
  301. alias = Alias.get_by(email=address)
  302. if not alias:
  303. LOG.d("alias %s not exist. Try to see if it can be created on the fly", address)
  304. alias = try_auto_create(address)
  305. if not alias:
  306. LOG.d("alias %s cannot be created on-the-fly, return 550", address)
  307. return [(False, "550 SL E3")]
  308. contact = get_or_create_contact(msg["From"], envelope.mail_from, alias)
  309. email_log = EmailLog.create(contact_id=contact.id, user_id=contact.user_id)
  310. if not alias.enabled:
  311. LOG.d("%s is disabled, do not forward", alias)
  312. email_log.blocked = True
  313. db.session.commit()
  314. # do not return 5** to allow user to receive emails later when alias is enabled
  315. return [(True, "250 Message accepted for delivery")]
  316. user = alias.user
  317. ret = []
  318. for mailbox in alias.mailboxes:
  319. ret.append(
  320. forward_email_to_mailbox(
  321. alias, msg, email_log, contact, envelope, smtp, mailbox, user
  322. )
  323. )
  324. return ret
  325. def forward_email_to_mailbox(
  326. alias,
  327. msg: Message,
  328. email_log: EmailLog,
  329. contact: Contact,
  330. envelope,
  331. smtp: SMTP,
  332. mailbox,
  333. user,
  334. ) -> (bool, str):
  335. LOG.d("Forward %s -> %s -> %s", contact, alias, mailbox)
  336. is_spam, spam_status = get_spam_info(msg)
  337. if is_spam:
  338. LOG.warning("Email detected as spam. Alias: %s, from: %s", alias, contact)
  339. email_log.is_spam = True
  340. email_log.spam_status = spam_status
  341. handle_spam(contact, alias, msg, user, mailbox.email, email_log)
  342. return False, "550 SL E1"
  343. # create PGP email if needed
  344. if mailbox.pgp_finger_print and user.is_premium() and not alias.disable_pgp:
  345. LOG.d("Encrypt message using mailbox %s", mailbox)
  346. try:
  347. msg = prepare_pgp_message(msg, mailbox.pgp_finger_print)
  348. except PGPException:
  349. LOG.error(
  350. "Cannot encrypt message %s -> %s. %s %s", contact, alias, mailbox, user
  351. )
  352. # so the client can retry later
  353. return False, "421 SL E12"
  354. # add custom header
  355. add_or_replace_header(msg, "X-SimpleLogin-Type", "Forward")
  356. # remove reply-to & sender header if present
  357. delete_header(msg, "Reply-To")
  358. delete_header(msg, "Sender")
  359. delete_header(msg, _IP_HEADER)
  360. add_or_replace_header(msg, _MAILBOX_ID_HEADER, str(mailbox.id))
  361. # change the from header so the sender comes from @SL
  362. # so it can pass DMARC check
  363. # replace the email part in from: header
  364. contact_from_header = msg["From"]
  365. new_from_header = contact.new_addr()
  366. add_or_replace_header(msg, "From", new_from_header)
  367. LOG.d("new_from_header:%s, old header %s", new_from_header, contact_from_header)
  368. # replace CC & To emails by reply-email for all emails that are not alias
  369. replace_header_when_forward(msg, alias, "Cc")
  370. replace_header_when_forward(msg, alias, "To")
  371. # append alias into the TO header if it's not present in To or CC
  372. if should_append_alias(msg, alias.email):
  373. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  374. if msg["To"]:
  375. to_header = msg["To"] + "," + alias.email
  376. else:
  377. to_header = alias.email
  378. add_or_replace_header(msg, "To", to_header.strip())
  379. # add List-Unsubscribe header
  380. if UNSUBSCRIBER:
  381. unsubscribe_link = f"mailto:{UNSUBSCRIBER}?subject={alias.id}="
  382. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  383. else:
  384. unsubscribe_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  385. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  386. add_or_replace_header(
  387. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  388. )
  389. add_dkim_signature(msg, EMAIL_DOMAIN)
  390. LOG.d(
  391. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  392. contact.website_email,
  393. mailbox.email,
  394. envelope.mail_options,
  395. envelope.rcpt_options,
  396. )
  397. # smtp.send_message has UnicodeEncodeErroremail issue
  398. # encode message raw directly instead
  399. smtp.sendmail(
  400. contact.reply_email,
  401. mailbox.email,
  402. msg.as_bytes(),
  403. envelope.mail_options,
  404. envelope.rcpt_options,
  405. )
  406. db.session.commit()
  407. return True, "250 Message accepted for delivery"
  408. def handle_reply(envelope, smtp: SMTP, msg: Message, rcpt_to: str) -> (bool, str):
  409. """
  410. return whether an email has been delivered and
  411. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  412. """
  413. reply_email = rcpt_to.lower().strip()
  414. # reply_email must end with EMAIL_DOMAIN
  415. if not reply_email.endswith(EMAIL_DOMAIN):
  416. LOG.warning(f"Reply email {reply_email} has wrong domain")
  417. return False, "550 SL E2"
  418. contact = Contact.get_by(reply_email=reply_email)
  419. if not contact:
  420. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  421. return False, "550 SL E4"
  422. alias = contact.alias
  423. address: str = contact.alias.email
  424. alias_domain = address[address.find("@") + 1 :]
  425. # alias must end with one of the ALIAS_DOMAINS or custom-domain
  426. if not email_belongs_to_alias_domains(alias.email):
  427. if not CustomDomain.get_by(domain=alias_domain):
  428. return False, "550 SL E5"
  429. user = alias.user
  430. mail_from = envelope.mail_from.lower().strip()
  431. # bounce email initiated by Postfix
  432. # can happen in case emails cannot be delivered to user-email
  433. # in this case Postfix will try to send a bounce report to original sender, which is
  434. # the "reply email"
  435. if mail_from == "<>":
  436. LOG.warning(
  437. "Bounce when sending to alias %s from %s, user %s", alias, contact, user,
  438. )
  439. handle_bounce(contact, alias, msg, user)
  440. return False, "550 SL E6"
  441. mailbox = Mailbox.get_by(email=mail_from, user_id=user.id)
  442. if not mailbox or mailbox not in alias.mailboxes:
  443. # only mailbox can send email to the reply-email
  444. handle_unknown_mailbox(envelope, msg, reply_email, user, alias)
  445. return False, "550 SL E7"
  446. if ENFORCE_SPF and mailbox.force_spf:
  447. ip = msg[_IP_HEADER]
  448. if not spf_pass(ip, envelope, mailbox, user, alias, contact.website_email, msg):
  449. # cannot use 4** here as sender will retry. 5** because that generates bounce report
  450. return True, "250 SL E11"
  451. delete_header(msg, _IP_HEADER)
  452. delete_header(msg, "DKIM-Signature")
  453. delete_header(msg, "Received")
  454. # make the email comes from alias
  455. from_header = alias.email
  456. # add alias name from alias
  457. if alias.name:
  458. LOG.d("Put alias name in from header")
  459. from_header = formataddr((alias.name, alias.email))
  460. elif alias.custom_domain:
  461. LOG.d("Put domain default alias name in from header")
  462. # add alias name from domain
  463. if alias.custom_domain.name:
  464. from_header = formataddr((alias.custom_domain.name, alias.email))
  465. add_or_replace_header(msg, "From", from_header)
  466. # some email providers like ProtonMail adds automatically the Reply-To field
  467. # make sure to delete it
  468. delete_header(msg, "Reply-To")
  469. # remove sender header if present as this could reveal user real email
  470. delete_header(msg, "Sender")
  471. delete_header(msg, "X-Sender")
  472. replace_header_when_reply(msg, alias, "To")
  473. replace_header_when_reply(msg, alias, "Cc")
  474. # Received-SPF is injected by postfix-policyd-spf-python can reveal user original email
  475. delete_header(msg, "Received-SPF")
  476. LOG.d(
  477. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  478. alias.email,
  479. contact.website_email,
  480. envelope.mail_options,
  481. envelope.rcpt_options,
  482. )
  483. # replace "ra+string@simplelogin.co" by the contact email in the email body
  484. # as this is usually included when replying
  485. if user.replace_reverse_alias:
  486. if msg.is_multipart():
  487. for part in msg.walk():
  488. if part.get_content_maintype() != "text":
  489. continue
  490. part = replace_str_in_msg(part, reply_email, contact.website_email)
  491. else:
  492. msg = replace_str_in_msg(msg, reply_email, contact.website_email)
  493. if alias_domain in ALIAS_DOMAINS:
  494. add_dkim_signature(msg, alias_domain)
  495. # add DKIM-Signature for custom-domain alias
  496. else:
  497. custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain)
  498. if custom_domain.dkim_verified:
  499. add_dkim_signature(msg, alias_domain)
  500. # create PGP email if needed
  501. if contact.pgp_finger_print and user.is_premium():
  502. LOG.d("Encrypt message for contact %s", contact)
  503. try:
  504. msg = prepare_pgp_message(msg, contact.pgp_finger_print)
  505. except PGPException:
  506. LOG.error(
  507. "Cannot encrypt message %s -> %s. %s %s", alias, contact, mailbox, user
  508. )
  509. # so the client can retry later
  510. return False, "421 SL E13"
  511. smtp.sendmail(
  512. alias.email,
  513. contact.website_email,
  514. msg.as_bytes(),
  515. envelope.mail_options,
  516. envelope.rcpt_options,
  517. )
  518. EmailLog.create(contact_id=contact.id, is_reply=True, user_id=contact.user_id)
  519. db.session.commit()
  520. return True, "250 Message accepted for delivery"
  521. def spf_pass(
  522. ip: str,
  523. envelope,
  524. mailbox: Mailbox,
  525. user: User,
  526. alias: Alias,
  527. contact_email: str,
  528. msg: Message,
  529. ) -> bool:
  530. if ip:
  531. LOG.d("Enforce SPF")
  532. try:
  533. r = spf.check2(i=ip, s=envelope.mail_from.lower(), h=None)
  534. except Exception:
  535. LOG.error("SPF error, mailbox %s, ip %s", mailbox.email, ip)
  536. else:
  537. # TODO: Handle temperr case (e.g. dns timeout)
  538. # only an absolute pass, or no SPF policy at all is 'valid'
  539. if r[0] not in ["pass", "none"]:
  540. LOG.warning(
  541. "SPF fail for mailbox %s, reason %s, failed IP %s",
  542. mailbox.email,
  543. r[0],
  544. ip,
  545. )
  546. send_email_with_rate_control(
  547. user,
  548. ALERT_SPF,
  549. mailbox.email,
  550. f"SimpleLogin Alert: attempt to send emails from your alias {alias.email} from unknown IP Address",
  551. render(
  552. "transactional/spf-fail.txt",
  553. name=user.name,
  554. alias=alias.email,
  555. ip=ip,
  556. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  557. to_email=contact_email,
  558. subject=msg["Subject"],
  559. time=arrow.now(),
  560. ),
  561. render(
  562. "transactional/spf-fail.html",
  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. )
  572. return False
  573. else:
  574. LOG.warning(
  575. "Could not find %s header %s -> %s",
  576. _IP_HEADER,
  577. mailbox.email,
  578. contact_email,
  579. )
  580. return True
  581. def handle_unknown_mailbox(envelope, msg, reply_email: str, user: User, alias: Alias):
  582. LOG.warning(
  583. f"Reply email can only be used by mailbox. "
  584. f"Actual mail_from: %s. msg from header: %s, reverse-alias %s, %s %s",
  585. envelope.mail_from,
  586. msg["From"],
  587. reply_email,
  588. alias,
  589. user,
  590. )
  591. send_email_with_rate_control(
  592. user,
  593. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  594. user.email,
  595. f"Reply from your alias {alias.email} only works from your mailbox",
  596. render(
  597. "transactional/reply-must-use-personal-email.txt",
  598. name=user.name,
  599. alias=alias,
  600. sender=envelope.mail_from,
  601. ),
  602. render(
  603. "transactional/reply-must-use-personal-email.html",
  604. name=user.name,
  605. alias=alias,
  606. sender=envelope.mail_from,
  607. ),
  608. )
  609. # Notify sender that they cannot send emails to this address
  610. send_email_with_rate_control(
  611. user,
  612. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  613. envelope.mail_from,
  614. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  615. render(
  616. "transactional/send-from-alias-from-unknown-sender.txt",
  617. sender=envelope.mail_from,
  618. reply_email=reply_email,
  619. ),
  620. render(
  621. "transactional/send-from-alias-from-unknown-sender.html",
  622. sender=envelope.mail_from,
  623. reply_email=reply_email,
  624. ),
  625. )
  626. def handle_bounce(contact: Contact, alias: Alias, msg: Message, user: User):
  627. address = alias.email
  628. email_log: EmailLog = EmailLog.create(
  629. contact_id=contact.id, bounced=True, user_id=contact.user_id
  630. )
  631. db.session.commit()
  632. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  633. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  634. # <<< Store the bounced email >>>
  635. # generate a name for the email
  636. random_name = str(uuid.uuid4())
  637. full_report_path = f"refused-emails/full-{random_name}.eml"
  638. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  639. file_path = None
  640. mailbox = alias.mailbox
  641. orig_msg = get_orig_message_from_bounce(msg)
  642. if not orig_msg:
  643. # Some MTA does not return the original message in bounce message
  644. # nothing we can do here
  645. LOG.warning(
  646. "Cannot parse original message from bounce message %s %s %s %s",
  647. alias,
  648. user,
  649. contact,
  650. full_report_path,
  651. )
  652. else:
  653. file_path = f"refused-emails/{random_name}.eml"
  654. s3.upload_email_from_bytesio(
  655. file_path, BytesIO(orig_msg.as_bytes()), random_name
  656. )
  657. # <<< END Store the bounced email >>>
  658. mailbox_id = int(orig_msg[_MAILBOX_ID_HEADER])
  659. mailbox = Mailbox.get(mailbox_id)
  660. if not mailbox or mailbox.user_id != user.id:
  661. LOG.error(
  662. "Tampered message mailbox_id %s, %s, %s, %s %s",
  663. mailbox_id,
  664. user,
  665. alias,
  666. contact,
  667. full_report_path,
  668. )
  669. # use the alias default mailbox
  670. mailbox = alias.mailbox
  671. refused_email = RefusedEmail.create(
  672. path=file_path, full_report_path=full_report_path, user_id=user.id
  673. )
  674. db.session.flush()
  675. email_log.refused_email_id = refused_email.id
  676. email_log.bounced_mailbox_id = mailbox.id
  677. db.session.commit()
  678. LOG.d("Create refused email %s", refused_email)
  679. refused_email_url = (
  680. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  681. )
  682. # inform user if this is the first bounced email
  683. if nb_bounced == 1:
  684. LOG.d(
  685. "Inform user %s about bounced email sent by %s to alias %s",
  686. user,
  687. contact.website_email,
  688. address,
  689. )
  690. send_email_with_rate_control(
  691. user,
  692. ALERT_BOUNCE_EMAIL,
  693. # use user mail here as only user is authenticated to see the refused email
  694. user.email,
  695. f"Email from {contact.website_email} to {address} cannot be delivered to your inbox",
  696. render(
  697. "transactional/bounced-email.txt",
  698. name=user.name,
  699. alias=alias,
  700. website_email=contact.website_email,
  701. disable_alias_link=disable_alias_link,
  702. refused_email_url=refused_email_url,
  703. mailbox_email=mailbox.email,
  704. ),
  705. render(
  706. "transactional/bounced-email.html",
  707. name=user.name,
  708. alias=alias,
  709. website_email=contact.website_email,
  710. disable_alias_link=disable_alias_link,
  711. refused_email_url=refused_email_url,
  712. mailbox_email=mailbox.email,
  713. ),
  714. # cannot include bounce email as it can contain spammy text
  715. # bounced_email=msg,
  716. )
  717. # disable the alias the second time email is bounced
  718. elif nb_bounced >= 2:
  719. LOG.d(
  720. "Bounce happens again with alias %s from %s. Disable alias now ",
  721. address,
  722. contact.website_email,
  723. )
  724. if alias.cannot_be_disabled:
  725. LOG.warning("%s cannot be disabled", alias)
  726. else:
  727. alias.enabled = False
  728. db.session.commit()
  729. send_email_with_rate_control(
  730. user,
  731. ALERT_BOUNCE_EMAIL,
  732. # use user mail here as only user is authenticated to see the refused email
  733. user.email,
  734. f"Alias {address} has been disabled due to second undelivered email from {contact.website_email}",
  735. render(
  736. "transactional/automatic-disable-alias.txt",
  737. name=user.name,
  738. alias=alias,
  739. website_email=contact.website_email,
  740. refused_email_url=refused_email_url,
  741. mailbox_email=mailbox.email,
  742. ),
  743. render(
  744. "transactional/automatic-disable-alias.html",
  745. name=user.name,
  746. alias=alias,
  747. website_email=contact.website_email,
  748. refused_email_url=refused_email_url,
  749. mailbox_email=mailbox.email,
  750. ),
  751. # cannot include bounce email as it can contain spammy text
  752. # bounced_email=msg,
  753. )
  754. def handle_spam(
  755. contact: Contact,
  756. alias: Alias,
  757. msg: Message,
  758. user: User,
  759. mailbox_email: str,
  760. email_log: EmailLog,
  761. ):
  762. # Store the report & original email
  763. orig_msg = get_orig_message_from_spamassassin_report(msg)
  764. # generate a name for the email
  765. random_name = str(uuid.uuid4())
  766. full_report_path = f"spams/full-{random_name}.eml"
  767. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  768. file_path = None
  769. if orig_msg:
  770. file_path = f"spams/{random_name}.eml"
  771. s3.upload_email_from_bytesio(
  772. file_path, BytesIO(orig_msg.as_bytes()), random_name
  773. )
  774. refused_email = RefusedEmail.create(
  775. path=file_path, full_report_path=full_report_path, user_id=user.id
  776. )
  777. db.session.flush()
  778. email_log.refused_email_id = refused_email.id
  779. db.session.commit()
  780. LOG.d("Create spam email %s", refused_email)
  781. refused_email_url = (
  782. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  783. )
  784. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  785. # inform user
  786. LOG.d(
  787. "Inform user %s about spam email sent by %s to alias %s",
  788. user,
  789. contact.website_email,
  790. alias.email,
  791. )
  792. send_email_with_rate_control(
  793. user,
  794. ALERT_SPAM_EMAIL,
  795. mailbox_email,
  796. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  797. render(
  798. "transactional/spam-email.txt",
  799. name=user.name,
  800. alias=alias,
  801. website_email=contact.website_email,
  802. disable_alias_link=disable_alias_link,
  803. refused_email_url=refused_email_url,
  804. ),
  805. render(
  806. "transactional/spam-email.html",
  807. name=user.name,
  808. alias=alias,
  809. website_email=contact.website_email,
  810. disable_alias_link=disable_alias_link,
  811. refused_email_url=refused_email_url,
  812. ),
  813. )
  814. def handle_unsubscribe(envelope: Envelope):
  815. msg = email.message_from_bytes(envelope.original_content)
  816. # format: alias_id:
  817. subject = msg["Subject"]
  818. try:
  819. # subject has the format {alias.id}=
  820. if subject.endswith("="):
  821. alias_id = int(subject[:-1])
  822. # some email providers might strip off the = suffix
  823. else:
  824. alias_id = int(subject)
  825. alias = Alias.get(alias_id)
  826. except Exception:
  827. LOG.warning("Cannot parse alias from subject %s", msg["Subject"])
  828. return "550 SL E8"
  829. if not alias:
  830. LOG.warning("No such alias %s", alias_id)
  831. return "550 SL E9"
  832. # This sender cannot unsubscribe
  833. mail_from = envelope.mail_from.lower().strip()
  834. mailbox = Mailbox.get_by(user_id=alias.user_id, email=mail_from)
  835. if not mailbox or mailbox not in alias.mailboxes:
  836. LOG.d("%s cannot disable alias %s", envelope.mail_from, alias)
  837. return "550 SL E10"
  838. # Sender is owner of this alias
  839. alias.enabled = False
  840. db.session.commit()
  841. user = alias.user
  842. enable_alias_url = URL + f"/dashboard/?highlight_alias_id={alias.id}"
  843. for mailbox in alias.mailboxes:
  844. send_email(
  845. mailbox.email,
  846. f"Alias {alias.email} has been disabled successfully",
  847. render(
  848. "transactional/unsubscribe-disable-alias.txt",
  849. user=user,
  850. alias=alias.email,
  851. enable_alias_url=enable_alias_url,
  852. ),
  853. render(
  854. "transactional/unsubscribe-disable-alias.html",
  855. user=user,
  856. alias=alias.email,
  857. enable_alias_url=enable_alias_url,
  858. ),
  859. )
  860. return "250 Unsubscribe request accepted"
  861. def handle(envelope: Envelope, smtp: SMTP) -> str:
  862. """Return SMTP status"""
  863. # unsubscribe request
  864. if UNSUBSCRIBER and envelope.rcpt_tos == [UNSUBSCRIBER]:
  865. LOG.d("Handle unsubscribe request from %s", envelope.mail_from)
  866. return handle_unsubscribe(envelope)
  867. # Whether it's necessary to apply greylisting
  868. if greylisting_needed(envelope.mail_from, envelope.rcpt_tos):
  869. LOG.warning(
  870. "Grey listing applied for %s %s", envelope.mail_from, envelope.rcpt_tos
  871. )
  872. return "421 SL Retry later"
  873. # result of all deliveries
  874. # each element is a couple of whether the delivery is successful and the smtp status
  875. res: [(bool, str)] = []
  876. for rcpt_to in envelope.rcpt_tos:
  877. msg = email.message_from_bytes(envelope.original_content)
  878. # Reply case
  879. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  880. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  881. LOG.debug(">>> Reply phase %s -> %s", envelope.mail_from, rcpt_to)
  882. is_delivered, smtp_status = handle_reply(envelope, smtp, msg, rcpt_to)
  883. res.append((is_delivered, smtp_status))
  884. else: # Forward case
  885. LOG.debug(">>> Forward phase %s -> %s", envelope.mail_from, rcpt_to)
  886. for is_delivered, smtp_status in handle_forward(
  887. envelope, smtp, msg, rcpt_to
  888. ):
  889. res.append((is_delivered, smtp_status))
  890. for (is_success, smtp_status) in res:
  891. # Consider all deliveries successful if 1 delivery is successful
  892. if is_success:
  893. return smtp_status
  894. # Failed delivery for all, return the first failure
  895. return res[0][1]
  896. class MailHandler:
  897. async def handle_DATA(self, server, session, envelope: Envelope):
  898. LOG.debug(
  899. "===>> New message, mail from %s, rctp tos %s ",
  900. envelope.mail_from,
  901. envelope.rcpt_tos,
  902. )
  903. if POSTFIX_SUBMISSION_TLS:
  904. smtp = SMTP(POSTFIX_SERVER, 587)
  905. smtp.starttls()
  906. else:
  907. smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25)
  908. app = new_app()
  909. with app.app_context():
  910. return handle(envelope, smtp)
  911. if __name__ == "__main__":
  912. controller = Controller(MailHandler(), hostname="0.0.0.0", port=20381)
  913. controller.start()
  914. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  915. if LOAD_PGP_EMAIL_HANDLER:
  916. LOG.warning("LOAD PGP keys")
  917. app = create_app()
  918. with app.app_context():
  919. load_pgp_public_keys()
  920. while True:
  921. time.sleep(2)