email_handler.py 37 KB

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