email_handler.py 42 KB

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