email_handler.py 35 KB

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