email_handler.py 41 KB

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