email_handler.py 41 KB

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