email_handler.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  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 argparse
  28. import asyncio
  29. import email
  30. import os
  31. import time
  32. import uuid
  33. from email import encoders
  34. from email.encoders import encode_noop
  35. from email.message import Message
  36. from email.mime.application import MIMEApplication
  37. from email.mime.multipart import MIMEMultipart
  38. from email.utils import formataddr, make_msgid, formatdate
  39. from io import BytesIO
  40. from smtplib import SMTP, SMTPRecipientsRefused
  41. from typing import List, Tuple, Optional
  42. import aiosmtpd
  43. import aiospamc
  44. import arrow
  45. import spf
  46. from aiosmtpd.controller import Controller
  47. from aiosmtpd.smtp import Envelope
  48. from sqlalchemy.exc import IntegrityError
  49. from app import pgp_utils, s3
  50. from app.alias_utils import try_auto_create
  51. from app.config import (
  52. EMAIL_DOMAIN,
  53. POSTFIX_SERVER,
  54. URL,
  55. POSTFIX_SUBMISSION_TLS,
  56. UNSUBSCRIBER,
  57. LOAD_PGP_EMAIL_HANDLER,
  58. ENFORCE_SPF,
  59. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  60. ALERT_BOUNCE_EMAIL,
  61. ALERT_SPAM_EMAIL,
  62. ALERT_SPF,
  63. POSTFIX_PORT,
  64. SENDER,
  65. SENDER_DIR,
  66. SPAMASSASSIN_HOST,
  67. MAX_SPAM_SCORE,
  68. MAX_REPLY_PHASE_SPAM_SCORE,
  69. ALERT_SEND_EMAIL_CYCLE,
  70. ALERT_MAILBOX_IS_ALIAS,
  71. PGP_SENDER_PRIVATE_KEY,
  72. ALERT_BOUNCE_EMAIL_REPLY_PHASE,
  73. )
  74. from app.email_utils import (
  75. send_email,
  76. add_dkim_signature,
  77. add_or_replace_header,
  78. delete_header,
  79. render,
  80. get_orig_message_from_bounce,
  81. delete_all_headers_except,
  82. get_addrs_from_header,
  83. get_spam_info,
  84. get_orig_message_from_spamassassin_report,
  85. parseaddr_unicode,
  86. send_email_with_rate_control,
  87. get_email_domain_part,
  88. copy,
  89. to_bytes,
  90. get_header_from_bounce,
  91. send_email_at_most_times,
  92. is_valid_alias_address_domain,
  93. should_add_dkim_signature,
  94. )
  95. from app.extensions import db
  96. from app.greylisting import greylisting_needed
  97. from app.log import LOG
  98. from app.models import (
  99. Alias,
  100. Contact,
  101. EmailLog,
  102. User,
  103. RefusedEmail,
  104. Mailbox,
  105. )
  106. from app.pgp_utils import PGPException, sign_data_with_pgpy, sign_data
  107. from app.spamassassin_utils import SpamAssassin
  108. from app.utils import random_string
  109. from init_app import load_pgp_public_keys
  110. from server import create_app, create_light_app
  111. # forward or reply
  112. _DIRECTION = "X-SimpleLogin-Type"
  113. _IP_HEADER = "X-SimpleLogin-Client-IP"
  114. _MAILBOX_ID_HEADER = "X-SimpleLogin-Mailbox-ID"
  115. _EMAIL_LOG_ID_HEADER = "X-SimpleLogin-EmailLog-ID"
  116. _MESSAGE_ID = "Message-ID"
  117. _ENVELOPE_FROM = "X-SimpleLogin-Envelope-From"
  118. _MIME_HEADERS = [
  119. "MIME-Version",
  120. "Content-Type",
  121. "Content-Disposition",
  122. "Content-Transfer-Encoding",
  123. ]
  124. _MIME_HEADERS = [h.lower() for h in _MIME_HEADERS]
  125. # fix the database connection leak issue
  126. # use this method instead of create_app
  127. def new_app():
  128. app = create_light_app()
  129. @app.teardown_appcontext
  130. def shutdown_session(response_or_exc):
  131. # same as shutdown_session() in flask-sqlalchemy but this is not enough
  132. db.session.remove()
  133. # dispose the engine too
  134. db.engine.dispose()
  135. return app
  136. def get_or_create_contact(
  137. contact_from_header: str, mail_from: str, alias: Alias
  138. ) -> Contact:
  139. """
  140. contact_from_header is the RFC 2047 format FROM header
  141. """
  142. # contact_from_header can be None, use mail_from in this case instead
  143. contact_from_header = contact_from_header or mail_from
  144. # force convert header to string, sometimes contact_from_header is Header object
  145. contact_from_header = str(contact_from_header)
  146. contact_name, contact_email = parseaddr_unicode(contact_from_header)
  147. if not contact_email:
  148. # From header is wrongly formatted, try with mail_from
  149. LOG.warning("From header is empty, parse mail_from %s %s", mail_from, alias)
  150. contact_name, contact_email = parseaddr_unicode(mail_from)
  151. if not contact_email:
  152. LOG.exception(
  153. "Cannot parse contact from from_header:%s, mail_from:%s",
  154. contact_from_header,
  155. mail_from,
  156. )
  157. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  158. if contact:
  159. if contact.name != contact_name:
  160. LOG.d(
  161. "Update contact %s name %s to %s",
  162. contact,
  163. contact.name,
  164. contact_name,
  165. )
  166. contact.name = contact_name
  167. db.session.commit()
  168. if contact.mail_from != mail_from:
  169. LOG.d(
  170. "Update contact %s mail_from %s to %s",
  171. contact,
  172. contact.mail_from,
  173. mail_from,
  174. )
  175. contact.mail_from = mail_from
  176. db.session.commit()
  177. if contact.from_header != contact_from_header:
  178. LOG.d(
  179. "Update contact %s from_header %s to %s",
  180. contact,
  181. contact.from_header,
  182. contact_from_header,
  183. )
  184. contact.from_header = contact_from_header
  185. db.session.commit()
  186. else:
  187. LOG.debug(
  188. "create contact for alias %s and contact %s",
  189. alias,
  190. contact_from_header,
  191. )
  192. reply_email = generate_reply_email()
  193. try:
  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. mail_from=mail_from,
  201. from_header=contact_from_header,
  202. )
  203. db.session.commit()
  204. except IntegrityError:
  205. LOG.warning("Contact %s %s already exist", alias, contact_email)
  206. db.session.rollback()
  207. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  208. return contact
  209. def replace_header_when_forward(msg: Message, alias: Alias, header: str):
  210. """
  211. Replace CC or To header by Reply emails in forward phase
  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. contact_name, contact_email = parseaddr_unicode(addr)
  220. # no transformation when alias is already in the header
  221. if contact_email == alias.email:
  222. new_addrs.append(addr)
  223. continue
  224. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  225. if contact:
  226. # update the contact name if needed
  227. if contact.name != contact_name:
  228. LOG.d(
  229. "Update contact %s name %s to %s",
  230. contact,
  231. contact.name,
  232. contact_name,
  233. )
  234. contact.name = contact_name
  235. db.session.commit()
  236. else:
  237. LOG.debug(
  238. "create contact for alias %s and email %s, header %s",
  239. alias,
  240. contact_email,
  241. header,
  242. )
  243. reply_email = generate_reply_email()
  244. try:
  245. contact = Contact.create(
  246. user_id=alias.user_id,
  247. alias_id=alias.id,
  248. website_email=contact_email,
  249. name=contact_name,
  250. reply_email=reply_email,
  251. is_cc=header.lower() == "cc",
  252. from_header=addr,
  253. )
  254. db.session.commit()
  255. except IntegrityError:
  256. LOG.warning("Contact %s %s already exist", alias, contact_email)
  257. db.session.rollback()
  258. contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
  259. new_addrs.append(contact.new_addr())
  260. if new_addrs:
  261. new_header = ",".join(new_addrs)
  262. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  263. add_or_replace_header(msg, header, new_header)
  264. else:
  265. LOG.d("Delete %s header, old value %s", header, msg[header])
  266. delete_header(msg, header)
  267. def replace_header_when_reply(msg: Message, alias: Alias, header: str):
  268. """
  269. Replace CC or To Reply emails by original emails
  270. """
  271. addrs = get_addrs_from_header(msg, header)
  272. # Nothing to do
  273. if not addrs:
  274. return
  275. new_addrs: [str] = []
  276. for addr in addrs:
  277. _, reply_email = parseaddr_unicode(addr)
  278. # no transformation when alias is already in the header
  279. if reply_email == alias.email:
  280. continue
  281. contact = Contact.get_by(reply_email=reply_email)
  282. if not contact:
  283. LOG.warning(
  284. "%s email in reply phase %s must be reply emails", header, reply_email
  285. )
  286. # still keep this email in header
  287. new_addrs.append(addr)
  288. else:
  289. new_addrs.append(formataddr((contact.name, contact.website_email)))
  290. if new_addrs:
  291. new_header = ",".join(new_addrs)
  292. LOG.d("Replace %s header, old: %s, new: %s", header, msg[header], new_header)
  293. add_or_replace_header(msg, header, new_header)
  294. else:
  295. LOG.d("delete the %s header. Old value %s", header, msg[header])
  296. delete_header(msg, header)
  297. def replace_str_in_msg(msg: Message, fr: str, to: str):
  298. if msg.get_content_maintype() != "text":
  299. return msg
  300. msg_payload = msg.get_payload(decode=True)
  301. if not msg_payload:
  302. return msg
  303. new_body = msg_payload.replace(fr.encode(), to.encode())
  304. # If utf-8 decoding fails, do not touch message part
  305. try:
  306. new_body = new_body.decode("utf-8")
  307. except:
  308. return msg
  309. cte = (
  310. msg["Content-Transfer-Encoding"].lower()
  311. if msg["Content-Transfer-Encoding"]
  312. else None
  313. )
  314. subtype = msg.get_content_subtype()
  315. delete_header(msg, "Content-Transfer-Encoding")
  316. delete_header(msg, "Content-Type")
  317. email.contentmanager.set_text_content(msg, new_body, subtype=subtype, cte=cte)
  318. return msg
  319. def generate_reply_email():
  320. # generate a reply_email, make sure it is unique
  321. # not use while loop to avoid infinite loop
  322. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  323. for _ in range(1000):
  324. if not Contact.get_by(reply_email=reply_email):
  325. # found!
  326. break
  327. reply_email = f"reply+{random_string(30)}@{EMAIL_DOMAIN}"
  328. return reply_email
  329. def should_append_alias(msg: Message, address: str):
  330. """whether an alias should be appended to TO header in message"""
  331. # # force convert header to string, sometimes addrs is Header object
  332. if msg["To"] and address.lower() in str(msg["To"]).lower():
  333. return False
  334. if msg["Cc"] and address.lower() in str(msg["Cc"]).lower():
  335. return False
  336. return True
  337. def prepare_pgp_message(
  338. orig_msg: Message, pgp_fingerprint: str, public_key: str, can_sign: bool = False
  339. ):
  340. msg = MIMEMultipart("encrypted", protocol="application/pgp-encrypted")
  341. # clone orig message to avoid modifying it
  342. clone_msg = copy(orig_msg)
  343. # copy all headers from original message except all standard MIME headers
  344. for i in reversed(range(len(clone_msg._headers))):
  345. header_name = clone_msg._headers[i][0].lower()
  346. if header_name.lower() not in _MIME_HEADERS:
  347. msg[header_name] = clone_msg._headers[i][1]
  348. # Delete unnecessary headers in clone_msg except _MIME_HEADERS to save space
  349. delete_all_headers_except(
  350. clone_msg,
  351. _MIME_HEADERS,
  352. )
  353. if clone_msg["Content-Type"] is None:
  354. LOG.d("Content-Type missing")
  355. clone_msg["Content-Type"] = "text/plain"
  356. if clone_msg["Mime-Version"] is None:
  357. LOG.d("Mime-Version missing")
  358. clone_msg["Mime-Version"] = "1.0"
  359. first = MIMEApplication(
  360. _subtype="pgp-encrypted", _encoder=encoders.encode_7or8bit, _data=""
  361. )
  362. first.set_payload("Version: 1")
  363. msg.attach(first)
  364. if can_sign and PGP_SENDER_PRIVATE_KEY:
  365. LOG.d("Sign msg")
  366. clone_msg = sign_msg(clone_msg)
  367. # use pgpy as fallback
  368. second = MIMEApplication(
  369. "octet-stream", _encoder=encoders.encode_7or8bit, name="encrypted.asc"
  370. )
  371. second.add_header("Content-Disposition", 'inline; filename="encrypted.asc"')
  372. # encrypt
  373. # use pgpy as fallback
  374. msg_bytes = clone_msg.as_bytes()
  375. try:
  376. encrypted_data = pgp_utils.encrypt_file(BytesIO(msg_bytes), pgp_fingerprint)
  377. second.set_payload(encrypted_data)
  378. except PGPException:
  379. LOG.exception("Cannot encrypt using python-gnupg, use pgpy")
  380. encrypted = pgp_utils.encrypt_file_with_pgpy(msg_bytes, public_key)
  381. second.set_payload(str(encrypted))
  382. msg.attach(second)
  383. return msg
  384. def sign_msg(msg: Message) -> Message:
  385. container = MIMEMultipart(
  386. "signed", protocol="application/pgp-signature", micalg="pgp-sha256"
  387. )
  388. container.attach(msg)
  389. signature = MIMEApplication(
  390. _subtype="pgp-signature", name="signature.asc", _data="", _encoder=encode_noop
  391. )
  392. signature.add_header("Content-Disposition", 'attachment; filename="signature.asc"')
  393. try:
  394. signature.set_payload(sign_data(msg.as_bytes().replace(b"\n", b"\r\n")))
  395. except Exception:
  396. LOG.exception("Cannot sign, try using pgpy")
  397. signature.set_payload(
  398. sign_data_with_pgpy(msg.as_bytes().replace(b"\n", b"\r\n"))
  399. )
  400. container.attach(signature)
  401. return container
  402. def handle_email_sent_to_ourself(alias, mailbox, msg: Message, user):
  403. # store the refused email
  404. random_name = str(uuid.uuid4())
  405. full_report_path = f"refused-emails/cycle-{random_name}.eml"
  406. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  407. refused_email = RefusedEmail.create(
  408. path=None, full_report_path=full_report_path, user_id=alias.user_id
  409. )
  410. db.session.commit()
  411. LOG.d("Create refused email %s", refused_email)
  412. # link available for 6 days as it gets deleted in 7 days
  413. refused_email_url = refused_email.get_url(expires_in=518400)
  414. send_email_at_most_times(
  415. user,
  416. ALERT_SEND_EMAIL_CYCLE,
  417. mailbox.email,
  418. f"Email sent to {alias.email} from its own mailbox {mailbox.email}",
  419. render(
  420. "transactional/cycle-email.txt",
  421. name=user.name or "",
  422. alias=alias,
  423. mailbox=mailbox,
  424. refused_email_url=refused_email_url,
  425. ),
  426. render(
  427. "transactional/cycle-email.html",
  428. name=user.name or "",
  429. alias=alias,
  430. mailbox=mailbox,
  431. refused_email_url=refused_email_url,
  432. ),
  433. )
  434. def handle_forward(envelope, msg: Message, rcpt_to: str) -> List[Tuple[bool, str]]:
  435. """return an array of SMTP status (is_success, smtp_status)
  436. is_success indicates whether an email has been delivered and
  437. smtp_status is the SMTP Status ("250 Message accepted", "550 Non-existent email address", etc)
  438. """
  439. address = rcpt_to # alias@SL
  440. alias = Alias.get_by(email=address)
  441. if not alias:
  442. LOG.d("alias %s not exist. Try to see if it can be created on the fly", address)
  443. alias = try_auto_create(address)
  444. if not alias:
  445. LOG.d("alias %s cannot be created on-the-fly, return 550", address)
  446. return [(False, "550 SL E3 Email not exist")]
  447. user = alias.user
  448. if user.disabled:
  449. LOG.warning("User %s disabled, disable forwarding emails for %s", user, alias)
  450. return [(False, "550 SL E20 Account disabled")]
  451. mail_from = envelope.mail_from
  452. for mb in alias.mailboxes:
  453. # email send from a mailbox to alias
  454. if mb.email == mail_from:
  455. LOG.warning("cycle email sent from %s to %s", mb, alias)
  456. handle_email_sent_to_ourself(alias, mb, msg, user)
  457. return [(True, "250 Message accepted for delivery")]
  458. # bounce email initiated by Postfix
  459. # can happen in case an email cannot be sent from an alias to a contact
  460. # in this case Postfix will send a bounce report to original sender, which is the alias
  461. if mail_from == "<>":
  462. LOG.warning("Bounce email sent to %s", alias)
  463. handle_bounce_reply_phase(alias, msg, user)
  464. return [(False, "550 SL E24 Email cannot be sent to contact")]
  465. contact = get_or_create_contact(msg["From"], envelope.mail_from, alias)
  466. email_log = EmailLog.create(contact_id=contact.id, user_id=contact.user_id)
  467. db.session.commit()
  468. if not alias.enabled:
  469. LOG.d("%s is disabled, do not forward", alias)
  470. email_log.blocked = True
  471. db.session.commit()
  472. # do not return 5** to allow user to receive emails later when alias is enabled
  473. return [(True, "250 Message accepted for delivery")]
  474. ret = []
  475. mailboxes = alias.mailboxes
  476. # no valid mailbox
  477. if not mailboxes:
  478. return [(False, "550 SL E16 invalid mailbox")]
  479. # no need to create a copy of message
  480. for mailbox in mailboxes:
  481. if not mailbox.verified:
  482. LOG.debug("Mailbox %s unverified, do not forward", mailbox)
  483. ret.append((False, "550 SL E19 unverified mailbox"))
  484. else:
  485. # create a copy of message for each forward
  486. ret.append(
  487. forward_email_to_mailbox(
  488. alias,
  489. copy(msg),
  490. email_log,
  491. contact,
  492. envelope,
  493. mailbox,
  494. user,
  495. )
  496. )
  497. return ret
  498. def forward_email_to_mailbox(
  499. alias,
  500. msg: Message,
  501. email_log: EmailLog,
  502. contact: Contact,
  503. envelope,
  504. mailbox,
  505. user,
  506. ) -> (bool, str):
  507. LOG.d("Forward %s -> %s -> %s", contact, alias, mailbox)
  508. if mailbox.disabled:
  509. LOG.debug("%s disabled, do not forward")
  510. return False, "550 SL E21 Disabled mailbox"
  511. # sanity check: make sure mailbox is not actually an alias
  512. if get_email_domain_part(alias.email) == get_email_domain_part(mailbox.email):
  513. LOG.warning(
  514. "Mailbox has the same domain as alias. %s -> %s -> %s",
  515. contact,
  516. alias,
  517. mailbox,
  518. )
  519. mailbox_url = f"{URL}/dashboard/mailbox/{mailbox.id}/"
  520. send_email_with_rate_control(
  521. user,
  522. ALERT_MAILBOX_IS_ALIAS,
  523. user.email,
  524. f"Your SimpleLogin mailbox {mailbox.email} cannot be an email alias",
  525. render(
  526. "transactional/mailbox-invalid.txt",
  527. name=user.name or "",
  528. mailbox=mailbox,
  529. mailbox_url=mailbox_url,
  530. ),
  531. render(
  532. "transactional/mailbox-invalid.html",
  533. name=user.name or "",
  534. mailbox=mailbox,
  535. mailbox_url=mailbox_url,
  536. ),
  537. max_nb_alert=1,
  538. )
  539. # retry later
  540. # so when user fixes the mailbox, the email can be delivered
  541. return False, "421 SL E14"
  542. # Spam check
  543. spam_status = ""
  544. is_spam = False
  545. if SPAMASSASSIN_HOST:
  546. start = time.time()
  547. spam_score = get_spam_score(msg)
  548. LOG.d(
  549. "%s -> %s - spam score %s in %s seconds",
  550. contact,
  551. alias,
  552. spam_score,
  553. time.time() - start,
  554. )
  555. email_log.spam_score = spam_score
  556. db.session.commit()
  557. if (user.max_spam_score and spam_score > user.max_spam_score) or (
  558. not user.max_spam_score and spam_score > MAX_SPAM_SCORE
  559. ):
  560. is_spam = True
  561. spam_status = "Spam detected by SpamAssassin server"
  562. else:
  563. is_spam, spam_status = get_spam_info(msg, max_score=user.max_spam_score)
  564. if is_spam:
  565. LOG.warning("Email detected as spam. Alias: %s, from: %s", alias, contact)
  566. email_log.is_spam = True
  567. email_log.spam_status = spam_status
  568. db.session.commit()
  569. handle_spam(contact, alias, msg, user, mailbox, email_log)
  570. return False, "550 SL E1 Email detected as spam"
  571. # create PGP email if needed
  572. if mailbox.pgp_finger_print and user.is_premium() and not alias.disable_pgp:
  573. LOG.d("Encrypt message using mailbox %s", mailbox)
  574. try:
  575. msg = prepare_pgp_message(
  576. msg, mailbox.pgp_finger_print, mailbox.pgp_public_key, can_sign=True
  577. )
  578. except PGPException:
  579. LOG.exception(
  580. "Cannot encrypt message %s -> %s. %s %s", contact, alias, mailbox, user
  581. )
  582. # so the client can retry later
  583. return False, "421 SL E12 Retry later"
  584. # add custom header
  585. add_or_replace_header(msg, _DIRECTION, "Forward")
  586. # remove reply-to & sender header if present
  587. delete_header(msg, "Reply-To")
  588. delete_header(msg, "Sender")
  589. delete_header(msg, _IP_HEADER)
  590. add_or_replace_header(msg, _MAILBOX_ID_HEADER, str(mailbox.id))
  591. add_or_replace_header(msg, _EMAIL_LOG_ID_HEADER, str(email_log.id))
  592. add_or_replace_header(msg, _MESSAGE_ID, make_msgid(str(email_log.id), EMAIL_DOMAIN))
  593. add_or_replace_header(msg, _ENVELOPE_FROM, envelope.mail_from)
  594. if not msg["Date"]:
  595. date_header = formatdate()
  596. msg["Date"] = date_header
  597. # change the from header so the sender comes from a reverse-alias
  598. # so it can pass DMARC check
  599. # replace the email part in from: header
  600. contact_from_header = msg["From"]
  601. new_from_header = contact.new_addr()
  602. add_or_replace_header(msg, "From", new_from_header)
  603. LOG.d("new_from_header:%s, old header %s", new_from_header, contact_from_header)
  604. # replace CC & To emails by reverse-alias for all emails that are not alias
  605. replace_header_when_forward(msg, alias, "Cc")
  606. replace_header_when_forward(msg, alias, "To")
  607. # append alias into the TO header if it's not present in To or CC
  608. if should_append_alias(msg, alias.email):
  609. LOG.d("append alias %s to TO header %s", alias, msg["To"])
  610. if msg["To"]:
  611. to_header = msg["To"] + "," + alias.email
  612. else:
  613. to_header = alias.email
  614. add_or_replace_header(msg, "To", to_header.strip())
  615. # add List-Unsubscribe header
  616. unsubscribe_link, via_email = alias.unsubscribe_link()
  617. add_or_replace_header(msg, "List-Unsubscribe", f"<{unsubscribe_link}>")
  618. if not via_email:
  619. add_or_replace_header(
  620. msg, "List-Unsubscribe-Post", "List-Unsubscribe=One-Click"
  621. )
  622. add_dkim_signature(msg, EMAIL_DOMAIN)
  623. LOG.d(
  624. "Forward mail from %s to %s, mail_options %s, rcpt_options %s ",
  625. contact.website_email,
  626. mailbox.email,
  627. envelope.mail_options,
  628. envelope.rcpt_options,
  629. )
  630. try:
  631. sl_sendmail(
  632. contact.reply_email,
  633. mailbox.email,
  634. msg,
  635. envelope.mail_options,
  636. envelope.rcpt_options,
  637. )
  638. except SMTPRecipientsRefused:
  639. # that means the mailbox is maybe invalid
  640. LOG.warning(
  641. "SMTPRecipientsRefused forward phase %s -> %s -> %s",
  642. contact,
  643. alias,
  644. mailbox,
  645. )
  646. # return 421 so Postfix can retry later
  647. return False, "421 SL E17 Retry later"
  648. else:
  649. db.session.commit()
  650. return True, "250 Message accepted for delivery"
  651. def handle_reply(envelope, msg: Message, rcpt_to: str) -> (bool, str):
  652. """
  653. return whether an email has been delivered and
  654. the smtp status ("250 Message accepted", "550 Non-existent email address", etc)
  655. """
  656. reply_email = rcpt_to
  657. # reply_email must end with EMAIL_DOMAIN
  658. if not reply_email.endswith(EMAIL_DOMAIN):
  659. LOG.warning(f"Reply email {reply_email} has wrong domain")
  660. return False, "550 SL E2"
  661. contact = Contact.get_by(reply_email=reply_email)
  662. if not contact:
  663. LOG.warning(f"No such forward-email with {reply_email} as reply-email")
  664. return False, "550 SL E4 Email not exist"
  665. alias = contact.alias
  666. address: str = contact.alias.email
  667. alias_domain = address[address.find("@") + 1 :]
  668. # Sanity check: verify alias domain is managed by SimpleLogin
  669. # scenario: a user have removed a domain but due to a bug, the aliases are still there
  670. if not is_valid_alias_address_domain(alias.email):
  671. LOG.exception("%s domain isn't known", alias)
  672. return False, "550 SL E5"
  673. user = alias.user
  674. mail_from = envelope.mail_from
  675. if user.disabled:
  676. LOG.exception(
  677. "User %s disabled, disable sending emails from %s to %s",
  678. user,
  679. alias,
  680. contact,
  681. )
  682. return [(False, "550 SL E20 Account disabled")]
  683. # bounce email initiated by Postfix
  684. # can happen in case emails cannot be delivered to user-email
  685. # in this case Postfix will try to send a bounce report to original sender, which is
  686. # the "reply email"
  687. if mail_from == "<>":
  688. LOG.warning(
  689. "Bounce when sending to alias %s from %s, user %s",
  690. alias,
  691. contact,
  692. user,
  693. )
  694. handle_bounce(contact, alias, msg, user)
  695. return False, "550 SL E6"
  696. # Anti-spoofing
  697. mailbox = get_mailbox_from_mail_from(mail_from, alias)
  698. if not mailbox:
  699. if alias.disable_email_spoofing_check:
  700. # ignore this error, use default alias mailbox
  701. LOG.warning(
  702. "ignore unknown sender to reverse-alias %s: %s -> %s",
  703. mail_from,
  704. alias,
  705. contact,
  706. )
  707. mailbox = alias.mailbox
  708. else:
  709. # only mailbox can send email to the reply-email
  710. handle_unknown_mailbox(envelope, msg, reply_email, user, alias, contact)
  711. return False, "550 SL E7"
  712. if ENFORCE_SPF and mailbox.force_spf and not alias.disable_email_spoofing_check:
  713. ip = msg[_IP_HEADER]
  714. if not spf_pass(ip, envelope, mailbox, user, alias, contact.website_email, msg):
  715. # cannot use 4** here as sender will retry. 5** because that generates bounce report
  716. return True, "250 SL E11"
  717. email_log = EmailLog.create(
  718. contact_id=contact.id, is_reply=True, user_id=contact.user_id
  719. )
  720. # Spam check
  721. spam_status = ""
  722. is_spam = False
  723. # do not use user.max_spam_score here
  724. if SPAMASSASSIN_HOST:
  725. start = time.time()
  726. spam_score = get_spam_score(msg)
  727. LOG.d(
  728. "%s -> %s - spam score %s in %s seconds",
  729. alias,
  730. contact,
  731. spam_score,
  732. time.time() - start,
  733. )
  734. email_log.spam_score = spam_score
  735. if spam_score > MAX_REPLY_PHASE_SPAM_SCORE:
  736. is_spam = True
  737. spam_status = "Spam detected by SpamAssassin server"
  738. else:
  739. is_spam, spam_status = get_spam_info(msg, max_score=MAX_REPLY_PHASE_SPAM_SCORE)
  740. if is_spam:
  741. LOG.exception(
  742. "Reply phase - email sent from %s to %s detected as spam", alias, contact
  743. )
  744. email_log.is_spam = True
  745. email_log.spam_status = spam_status
  746. db.session.commit()
  747. handle_spam(contact, alias, msg, user, mailbox, email_log, is_reply=True)
  748. return False, "550 SL E15 Email detected as spam"
  749. delete_all_headers_except(
  750. msg,
  751. [
  752. "From",
  753. "To",
  754. "Cc",
  755. "Subject",
  756. ]
  757. + _MIME_HEADERS,
  758. )
  759. # replace "ra+string@simplelogin.co" by the contact email in the email body
  760. # as this is usually included when replying
  761. if user.replace_reverse_alias:
  762. if msg.is_multipart():
  763. for part in msg.walk():
  764. if part.get_content_maintype() != "text":
  765. continue
  766. part = replace_str_in_msg(part, reply_email, contact.website_email)
  767. else:
  768. msg = replace_str_in_msg(msg, reply_email, contact.website_email)
  769. # create PGP email if needed
  770. if contact.pgp_finger_print and user.is_premium():
  771. LOG.d("Encrypt message for contact %s", contact)
  772. try:
  773. msg = prepare_pgp_message(
  774. msg, contact.pgp_finger_print, contact.pgp_public_key
  775. )
  776. except PGPException:
  777. LOG.exception(
  778. "Cannot encrypt message %s -> %s. %s %s", alias, contact, mailbox, user
  779. )
  780. # to not save the email_log
  781. db.session.rollback()
  782. # return 421 so the client can retry later
  783. return False, "421 SL E13 Retry later"
  784. # save the email_log to DB
  785. db.session.commit()
  786. # make the email comes from alias
  787. from_header = alias.email
  788. # add alias name from alias
  789. if alias.name:
  790. LOG.d("Put alias name in from header")
  791. from_header = formataddr((alias.name, alias.email))
  792. elif alias.custom_domain:
  793. LOG.d("Put domain default alias name in from header")
  794. # add alias name from domain
  795. if alias.custom_domain.name:
  796. from_header = formataddr((alias.custom_domain.name, alias.email))
  797. add_or_replace_header(msg, "From", from_header)
  798. replace_header_when_reply(msg, alias, "To")
  799. replace_header_when_reply(msg, alias, "Cc")
  800. add_or_replace_header(
  801. msg,
  802. _MESSAGE_ID,
  803. make_msgid(str(email_log.id), get_email_domain_part(alias.email)),
  804. )
  805. date_header = formatdate()
  806. msg["Date"] = date_header
  807. msg[_DIRECTION] = "Reply"
  808. msg[_MAILBOX_ID_HEADER] = str(mailbox.id)
  809. msg[_EMAIL_LOG_ID_HEADER] = str(email_log.id)
  810. LOG.d(
  811. "send email from %s to %s, mail_options:%s,rcpt_options:%s",
  812. alias.email,
  813. contact.website_email,
  814. envelope.mail_options,
  815. envelope.rcpt_options,
  816. )
  817. if should_add_dkim_signature(alias_domain):
  818. add_dkim_signature(msg, alias_domain)
  819. try:
  820. sl_sendmail(
  821. alias.email,
  822. contact.website_email,
  823. msg,
  824. envelope.mail_options,
  825. envelope.rcpt_options,
  826. )
  827. except Exception:
  828. # to not save the email_log
  829. db.session.rollback()
  830. LOG.warning("Cannot send email from %s to %s", alias, contact)
  831. send_email(
  832. mailbox.email,
  833. f"Email cannot be sent to {contact.email} from {alias.email}",
  834. render(
  835. "transactional/reply-error.txt",
  836. user=user,
  837. alias=alias,
  838. contact=contact,
  839. contact_domain=get_email_domain_part(contact.email),
  840. ),
  841. render(
  842. "transactional/reply-error.html",
  843. user=user,
  844. alias=alias,
  845. contact=contact,
  846. contact_domain=get_email_domain_part(contact.email),
  847. ),
  848. )
  849. # return 250 even if error as user is already informed of the incident and can retry sending the email
  850. return True, "250 Message accepted for delivery"
  851. def get_mailbox_from_mail_from(mail_from: str, alias) -> Optional[Mailbox]:
  852. """return the corresponding mailbox given the mail_from and alias
  853. Usually the mail_from=mailbox.email but it can also be one of the authorized address
  854. """
  855. for mailbox in alias.mailboxes:
  856. if mailbox.email == mail_from:
  857. return mailbox
  858. for address in mailbox.authorized_addresses:
  859. if address.email == mail_from:
  860. LOG.debug(
  861. "Found an authorized address for %s %s %s", alias, mailbox, address
  862. )
  863. return mailbox
  864. return None
  865. def spf_pass(
  866. ip: str,
  867. envelope,
  868. mailbox: Mailbox,
  869. user: User,
  870. alias: Alias,
  871. contact_email: str,
  872. msg: Message,
  873. ) -> bool:
  874. if ip:
  875. LOG.d("Enforce SPF")
  876. try:
  877. r = spf.check2(i=ip, s=envelope.mail_from, h=None)
  878. except Exception:
  879. LOG.exception("SPF error, mailbox %s, ip %s", mailbox.email, ip)
  880. else:
  881. # TODO: Handle temperr case (e.g. dns timeout)
  882. # only an absolute pass, or no SPF policy at all is 'valid'
  883. if r[0] not in ["pass", "none"]:
  884. LOG.warning(
  885. "SPF fail for mailbox %s, reason %s, failed IP %s",
  886. mailbox.email,
  887. r[0],
  888. ip,
  889. )
  890. send_email_with_rate_control(
  891. user,
  892. ALERT_SPF,
  893. mailbox.email,
  894. f"SimpleLogin Alert: attempt to send emails from your alias {alias.email} from unknown IP Address",
  895. render(
  896. "transactional/spf-fail.txt",
  897. name=user.name,
  898. alias=alias.email,
  899. ip=ip,
  900. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  901. to_email=contact_email,
  902. subject=msg["Subject"],
  903. time=arrow.now(),
  904. ),
  905. render(
  906. "transactional/spf-fail.html",
  907. name=user.name,
  908. alias=alias.email,
  909. ip=ip,
  910. mailbox_url=URL + f"/dashboard/mailbox/{mailbox.id}#spf",
  911. to_email=contact_email,
  912. subject=msg["Subject"],
  913. time=arrow.now(),
  914. ),
  915. )
  916. return False
  917. else:
  918. LOG.warning(
  919. "Could not find %s header %s -> %s",
  920. _IP_HEADER,
  921. mailbox.email,
  922. contact_email,
  923. )
  924. return True
  925. def handle_unknown_mailbox(
  926. envelope, msg, reply_email: str, user: User, alias: Alias, contact: Contact
  927. ):
  928. LOG.warning(
  929. f"Reply email can only be used by mailbox. "
  930. f"Actual mail_from: %s. msg from header: %s, reverse-alias %s, %s %s %s",
  931. envelope.mail_from,
  932. msg["From"],
  933. reply_email,
  934. alias,
  935. user,
  936. contact,
  937. )
  938. authorize_address_link = (
  939. f"{URL}/dashboard/mailbox/{alias.mailbox_id}/#authorized-address"
  940. )
  941. mailbox_emails = [mailbox.email for mailbox in alias.mailboxes]
  942. send_email_with_rate_control(
  943. user,
  944. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  945. user.email,
  946. f"Attempt to use your alias {alias.email} from {envelope.mail_from}",
  947. render(
  948. "transactional/reply-must-use-personal-email.txt",
  949. name=user.name,
  950. alias=alias,
  951. sender=envelope.mail_from,
  952. authorize_address_link=authorize_address_link,
  953. mailbox_emails=mailbox_emails,
  954. ),
  955. render(
  956. "transactional/reply-must-use-personal-email.html",
  957. name=user.name,
  958. alias=alias,
  959. sender=envelope.mail_from,
  960. authorize_address_link=authorize_address_link,
  961. mailbox_emails=mailbox_emails,
  962. ),
  963. )
  964. # Notify sender that they cannot send emails to this address
  965. send_email_with_rate_control(
  966. user,
  967. ALERT_REVERSE_ALIAS_UNKNOWN_MAILBOX,
  968. envelope.mail_from,
  969. f"Your email ({envelope.mail_from}) is not allowed to send emails to {reply_email}",
  970. render(
  971. "transactional/send-from-alias-from-unknown-sender.txt",
  972. sender=envelope.mail_from,
  973. reply_email=reply_email,
  974. ),
  975. render(
  976. "transactional/send-from-alias-from-unknown-sender.html",
  977. sender=envelope.mail_from,
  978. reply_email=reply_email,
  979. ),
  980. )
  981. def handle_bounce(contact: Contact, alias: Alias, msg: Message, user: User):
  982. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  983. # Store the bounced email
  984. # generate a name for the email
  985. random_name = str(uuid.uuid4())
  986. full_report_path = f"refused-emails/full-{random_name}.eml"
  987. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  988. file_path = None
  989. mailbox = None
  990. email_log: EmailLog = None
  991. orig_msg = get_orig_message_from_bounce(msg)
  992. if not orig_msg:
  993. # Some MTA does not return the original message in bounce message
  994. # nothing we can do here
  995. LOG.warning(
  996. "Cannot parse original message from bounce message %s %s %s %s",
  997. alias,
  998. user,
  999. contact,
  1000. full_report_path,
  1001. )
  1002. else:
  1003. file_path = f"refused-emails/{random_name}.eml"
  1004. s3.upload_email_from_bytesio(
  1005. file_path, BytesIO(orig_msg.as_bytes()), random_name
  1006. )
  1007. try:
  1008. mailbox_id = int(orig_msg[_MAILBOX_ID_HEADER])
  1009. except TypeError:
  1010. LOG.warning(
  1011. "cannot parse mailbox from original message header %s",
  1012. orig_msg[_MAILBOX_ID_HEADER],
  1013. )
  1014. else:
  1015. mailbox = Mailbox.get(mailbox_id)
  1016. if not mailbox or mailbox.user_id != user.id:
  1017. LOG.exception(
  1018. "Tampered message mailbox_id %s, %s, %s, %s %s",
  1019. mailbox_id,
  1020. user,
  1021. alias,
  1022. contact,
  1023. full_report_path,
  1024. )
  1025. # cannot use this tampered mailbox, reset it
  1026. mailbox = None
  1027. # try to get the original email_log
  1028. try:
  1029. email_log_id = int(orig_msg[_EMAIL_LOG_ID_HEADER])
  1030. except TypeError:
  1031. LOG.warning(
  1032. "cannot parse email log from original message header %s",
  1033. orig_msg[_EMAIL_LOG_ID_HEADER],
  1034. )
  1035. else:
  1036. email_log = EmailLog.get(email_log_id)
  1037. refused_email = RefusedEmail.create(
  1038. path=file_path, full_report_path=full_report_path, user_id=user.id
  1039. )
  1040. db.session.flush()
  1041. LOG.d("Create refused email %s", refused_email)
  1042. if not mailbox:
  1043. LOG.debug("Try to get mailbox from bounce report")
  1044. try:
  1045. mailbox_id = int(get_header_from_bounce(msg, _MAILBOX_ID_HEADER))
  1046. except Exception:
  1047. LOG.warning("cannot get mailbox-id from bounce report, %s", refused_email)
  1048. else:
  1049. mailbox = Mailbox.get(mailbox_id)
  1050. if not mailbox or mailbox.user_id != user.id:
  1051. LOG.exception(
  1052. "Tampered message mailbox_id %s, %s, %s, %s %s",
  1053. mailbox_id,
  1054. user,
  1055. alias,
  1056. contact,
  1057. full_report_path,
  1058. )
  1059. mailbox = None
  1060. if not email_log:
  1061. LOG.d("Try to get email log from bounce report")
  1062. try:
  1063. email_log_id = int(get_header_from_bounce(msg, _EMAIL_LOG_ID_HEADER))
  1064. except Exception:
  1065. LOG.warning("cannot get email log id from bounce report, %s", refused_email)
  1066. else:
  1067. email_log = EmailLog.get(email_log_id)
  1068. # use the default mailbox as the last option
  1069. if not mailbox:
  1070. LOG.warning("Use %s default mailbox %s", alias, refused_email)
  1071. mailbox = alias.mailbox
  1072. # create a new email log as the last option
  1073. if not email_log:
  1074. LOG.warning("cannot get the original email_log, create a new one")
  1075. email_log: EmailLog = EmailLog.create(
  1076. contact_id=contact.id, user_id=contact.user_id
  1077. )
  1078. email_log.bounced = True
  1079. email_log.refused_email_id = refused_email.id
  1080. email_log.bounced_mailbox_id = mailbox.id
  1081. db.session.commit()
  1082. refused_email_url = (
  1083. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  1084. )
  1085. nb_bounced = EmailLog.filter_by(contact_id=contact.id, bounced=True).count()
  1086. if nb_bounced >= 2 and alias.cannot_be_disabled:
  1087. LOG.warning("%s cannot be disabled", alias)
  1088. # inform user if this is the first bounced email
  1089. if nb_bounced == 1 or (nb_bounced >= 2 and alias.cannot_be_disabled):
  1090. LOG.d(
  1091. "Inform user %s about bounced email sent by %s to alias %s",
  1092. user,
  1093. contact.website_email,
  1094. alias,
  1095. )
  1096. send_email_with_rate_control(
  1097. user,
  1098. ALERT_BOUNCE_EMAIL,
  1099. user.email,
  1100. f"Email from {contact.website_email} to {alias.email} cannot be delivered to your inbox",
  1101. render(
  1102. "transactional/bounced-email.txt",
  1103. name=user.name,
  1104. alias=alias,
  1105. website_email=contact.website_email,
  1106. disable_alias_link=disable_alias_link,
  1107. refused_email_url=refused_email_url,
  1108. mailbox_email=mailbox.email,
  1109. ),
  1110. render(
  1111. "transactional/bounced-email.html",
  1112. name=user.name,
  1113. alias=alias,
  1114. website_email=contact.website_email,
  1115. disable_alias_link=disable_alias_link,
  1116. refused_email_url=refused_email_url,
  1117. mailbox_email=mailbox.email,
  1118. ),
  1119. )
  1120. # disable the alias the second time email is bounced
  1121. elif nb_bounced >= 2:
  1122. LOG.d(
  1123. "Bounce happens again with alias %s from %s. Disable alias now ",
  1124. alias,
  1125. contact.website_email,
  1126. )
  1127. alias.enabled = False
  1128. db.session.commit()
  1129. send_email_with_rate_control(
  1130. user,
  1131. ALERT_BOUNCE_EMAIL,
  1132. user.email,
  1133. f"Alias {alias.email} has been disabled due to second undelivered email from {contact.website_email}",
  1134. render(
  1135. "transactional/automatic-disable-alias.txt",
  1136. name=user.name,
  1137. alias=alias,
  1138. website_email=contact.website_email,
  1139. refused_email_url=refused_email_url,
  1140. mailbox_email=mailbox.email,
  1141. ),
  1142. render(
  1143. "transactional/automatic-disable-alias.html",
  1144. name=user.name,
  1145. alias=alias,
  1146. website_email=contact.website_email,
  1147. refused_email_url=refused_email_url,
  1148. mailbox_email=mailbox.email,
  1149. ),
  1150. )
  1151. def handle_bounce_reply_phase(alias: Alias, msg: Message, user: User):
  1152. """
  1153. Handle bounce that is sent to alias
  1154. Happens when an email cannot be sent from an alias to a contact
  1155. """
  1156. try:
  1157. email_log_id = int(get_header_from_bounce(msg, _EMAIL_LOG_ID_HEADER))
  1158. except Exception:
  1159. # save the data for debugging
  1160. file_path = f"/tmp/{random_string(10)}.eml"
  1161. with open(file_path, "wb") as f:
  1162. f.write(msg.as_bytes())
  1163. LOG.exception(
  1164. "Cannot get email-log-id from bounced report, %s %s %s",
  1165. alias,
  1166. user,
  1167. file_path,
  1168. )
  1169. LOG.d("Msg:\n%s", msg)
  1170. return
  1171. email_log = EmailLog.get(email_log_id)
  1172. contact = email_log.contact
  1173. # Store the bounced email
  1174. # generate a name for the email
  1175. random_name = str(uuid.uuid4())
  1176. full_report_path = f"refused-emails/full-{random_name}.eml"
  1177. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  1178. orig_msg = get_orig_message_from_bounce(msg)
  1179. file_path = None
  1180. if orig_msg:
  1181. file_path = f"refused-emails/{random_name}.eml"
  1182. s3.upload_email_from_bytesio(
  1183. file_path, BytesIO(orig_msg.as_bytes()), random_name
  1184. )
  1185. refused_email = RefusedEmail.create(
  1186. path=file_path, full_report_path=full_report_path, user_id=user.id, commit=True
  1187. )
  1188. LOG.d("Create refused email %s", refused_email)
  1189. email_log.bounced = True
  1190. email_log.refused_email_id = refused_email.id
  1191. db.session.commit()
  1192. try:
  1193. mailbox_id = int(get_header_from_bounce(msg, _MAILBOX_ID_HEADER))
  1194. except Exception:
  1195. LOG.warning(
  1196. "cannot parse mailbox from bounce message report %s %s", alias, user
  1197. )
  1198. # fall back to the default mailbox
  1199. mailbox = alias.mailbox
  1200. else:
  1201. mailbox = Mailbox.get(mailbox_id)
  1202. email_log.bounced_mailbox_id = mailbox.id
  1203. db.session.commit()
  1204. refused_email_url = (
  1205. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  1206. )
  1207. LOG.d(
  1208. "Inform user %s about bounced email sent by %s to %s",
  1209. user,
  1210. alias,
  1211. contact,
  1212. )
  1213. send_email_with_rate_control(
  1214. user,
  1215. ALERT_BOUNCE_EMAIL_REPLY_PHASE,
  1216. mailbox.email,
  1217. f"Email cannot be sent to { contact.email } from your alias { alias.email }",
  1218. render(
  1219. "transactional/bounce-email-reply-phase.txt",
  1220. alias=alias,
  1221. contact=contact,
  1222. refused_email_url=refused_email_url,
  1223. ),
  1224. render(
  1225. "transactional/bounce-email-reply-phase.html",
  1226. alias=alias,
  1227. contact=contact,
  1228. refused_email_url=refused_email_url,
  1229. ),
  1230. )
  1231. def handle_spam(
  1232. contact: Contact,
  1233. alias: Alias,
  1234. msg: Message,
  1235. user: User,
  1236. mailbox: Mailbox,
  1237. email_log: EmailLog,
  1238. is_reply=False, # whether the email is in forward or reply phase
  1239. ):
  1240. # Store the report & original email
  1241. orig_msg = get_orig_message_from_spamassassin_report(msg)
  1242. # generate a name for the email
  1243. random_name = str(uuid.uuid4())
  1244. full_report_path = f"spams/full-{random_name}.eml"
  1245. s3.upload_email_from_bytesio(full_report_path, BytesIO(msg.as_bytes()), random_name)
  1246. file_path = None
  1247. if orig_msg:
  1248. file_path = f"spams/{random_name}.eml"
  1249. s3.upload_email_from_bytesio(
  1250. file_path, BytesIO(orig_msg.as_bytes()), random_name
  1251. )
  1252. refused_email = RefusedEmail.create(
  1253. path=file_path, full_report_path=full_report_path, user_id=user.id
  1254. )
  1255. db.session.flush()
  1256. email_log.refused_email_id = refused_email.id
  1257. db.session.commit()
  1258. LOG.d("Create spam email %s", refused_email)
  1259. refused_email_url = (
  1260. URL + f"/dashboard/refused_email?highlight_id=" + str(email_log.id)
  1261. )
  1262. disable_alias_link = f"{URL}/dashboard/unsubscribe/{alias.id}"
  1263. if is_reply:
  1264. LOG.d(
  1265. "Inform %s (%s) about spam email sent from alias %s to %s",
  1266. mailbox,
  1267. user,
  1268. alias,
  1269. contact,
  1270. )
  1271. send_email_with_rate_control(
  1272. user,
  1273. ALERT_SPAM_EMAIL,
  1274. mailbox.email,
  1275. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  1276. render(
  1277. "transactional/spam-email-reply-phase.txt",
  1278. name=user.name,
  1279. alias=alias,
  1280. website_email=contact.website_email,
  1281. disable_alias_link=disable_alias_link,
  1282. refused_email_url=refused_email_url,
  1283. ),
  1284. render(
  1285. "transactional/spam-email-reply-phase.html",
  1286. name=user.name,
  1287. alias=alias,
  1288. website_email=contact.website_email,
  1289. disable_alias_link=disable_alias_link,
  1290. refused_email_url=refused_email_url,
  1291. ),
  1292. )
  1293. else:
  1294. # inform user
  1295. LOG.d(
  1296. "Inform %s (%s) about spam email sent by %s to alias %s",
  1297. mailbox,
  1298. user,
  1299. contact,
  1300. alias,
  1301. )
  1302. send_email_with_rate_control(
  1303. user,
  1304. ALERT_SPAM_EMAIL,
  1305. mailbox.email,
  1306. f"Email from {contact.website_email} to {alias.email} is detected as spam",
  1307. render(
  1308. "transactional/spam-email.txt",
  1309. name=user.name,
  1310. alias=alias,
  1311. website_email=contact.website_email,
  1312. disable_alias_link=disable_alias_link,
  1313. refused_email_url=refused_email_url,
  1314. ),
  1315. render(
  1316. "transactional/spam-email.html",
  1317. name=user.name,
  1318. alias=alias,
  1319. website_email=contact.website_email,
  1320. disable_alias_link=disable_alias_link,
  1321. refused_email_url=refused_email_url,
  1322. ),
  1323. )
  1324. def handle_unsubscribe(envelope: Envelope) -> str:
  1325. """return the SMTP status"""
  1326. msg = email.message_from_bytes(envelope.original_content)
  1327. # format: alias_id:
  1328. subject = msg["Subject"]
  1329. try:
  1330. # subject has the format {alias.id}=
  1331. if subject.endswith("="):
  1332. alias_id = int(subject[:-1])
  1333. # {user.id}*
  1334. elif subject.endswith("*"):
  1335. user_id = int(subject[:-1])
  1336. return handle_unsubscribe_user(user_id, envelope.mail_from)
  1337. # some email providers might strip off the = suffix
  1338. else:
  1339. alias_id = int(subject)
  1340. alias = Alias.get(alias_id)
  1341. except Exception:
  1342. LOG.warning("Cannot parse alias from subject %s", msg["Subject"])
  1343. return "550 SL E8 Wrongly formatted subject"
  1344. if not alias:
  1345. LOG.warning("No such alias %s", alias_id)
  1346. return "550 SL E9 Email not exist"
  1347. # This sender cannot unsubscribe
  1348. mail_from = envelope.mail_from
  1349. # Only alias's owning mailbox can send the unsubscribe request
  1350. mailbox = get_mailbox_from_mail_from(mail_from, alias)
  1351. if not mailbox:
  1352. LOG.d("%s cannot disable alias %s", envelope.mail_from, alias)
  1353. return "550 SL E10 unauthorized"
  1354. # Sender is owner of this alias
  1355. alias.enabled = False
  1356. db.session.commit()
  1357. user = alias.user
  1358. enable_alias_url = URL + f"/dashboard/?highlight_alias_id={alias.id}"
  1359. for mailbox in alias.mailboxes:
  1360. send_email(
  1361. mailbox.email,
  1362. f"Alias {alias.email} has been disabled successfully",
  1363. render(
  1364. "transactional/unsubscribe-disable-alias.txt",
  1365. user=user,
  1366. alias=alias.email,
  1367. enable_alias_url=enable_alias_url,
  1368. ),
  1369. render(
  1370. "transactional/unsubscribe-disable-alias.html",
  1371. user=user,
  1372. alias=alias.email,
  1373. enable_alias_url=enable_alias_url,
  1374. ),
  1375. )
  1376. return "250 Unsubscribe request accepted"
  1377. def handle_unsubscribe_user(user_id: int, mail_from: str) -> str:
  1378. """return the SMTP status"""
  1379. user = User.get(user_id)
  1380. if not user:
  1381. LOG.exception("No such user %s %s", user_id, mail_from)
  1382. return "550 SL E22 so such user"
  1383. if mail_from != user.email:
  1384. LOG.exception("Unauthorized mail_from %s %s", user, mail_from)
  1385. return "550 SL E23 unsubscribe error"
  1386. user.notification = False
  1387. db.session.commit()
  1388. send_email(
  1389. user.email,
  1390. f"You have been unsubscribed from SimpleLogin newsletter",
  1391. render(
  1392. "transactional/unsubscribe-newsletter.txt",
  1393. user=user,
  1394. ),
  1395. render(
  1396. "transactional/unsubscribe-newsletter.html",
  1397. user=user,
  1398. ),
  1399. )
  1400. return "250 Unsubscribe request accepted"
  1401. def handle_sender_email(envelope: Envelope):
  1402. filename = (
  1403. arrow.now().format("YYYY-MM-DD_HH-mm-ss") + "_" + random_string(10) + ".eml"
  1404. )
  1405. filepath = os.path.join(SENDER_DIR, filename)
  1406. with open(filepath, "wb") as f:
  1407. f.write(envelope.original_content)
  1408. LOG.d("Write email to sender at %s", filepath)
  1409. msg = email.message_from_bytes(envelope.original_content)
  1410. orig = get_orig_message_from_bounce(msg)
  1411. if orig:
  1412. LOG.warning(
  1413. "Original message %s -> %s saved at %s", orig["From"], orig["To"], filepath
  1414. )
  1415. return "250 email to sender accepted"
  1416. def handle(envelope: Envelope) -> str:
  1417. """Return SMTP status"""
  1418. # sanitize mail_from, rcpt_tos
  1419. mail_from = envelope.mail_from.lower().strip().replace(" ", "")
  1420. rcpt_tos = [
  1421. rcpt_to.lower().strip().replace(" ", "") for rcpt_to in envelope.rcpt_tos
  1422. ]
  1423. envelope.mail_from = mail_from
  1424. envelope.rcpt_tos = rcpt_tos
  1425. # unsubscribe request
  1426. if UNSUBSCRIBER and rcpt_tos == [UNSUBSCRIBER]:
  1427. LOG.d("Handle unsubscribe request from %s", mail_from)
  1428. return handle_unsubscribe(envelope)
  1429. # emails sent to sender. Probably bounce emails
  1430. if SENDER and rcpt_tos == [SENDER]:
  1431. LOG.d("Handle email sent to sender from %s", mail_from)
  1432. return handle_sender_email(envelope)
  1433. # Whether it's necessary to apply greylisting
  1434. if greylisting_needed(mail_from, rcpt_tos):
  1435. LOG.warning("Grey listing applied for %s %s", mail_from, rcpt_tos)
  1436. return "421 SL Retry later"
  1437. # result of all deliveries
  1438. # each element is a couple of whether the delivery is successful and the smtp status
  1439. res: [(bool, str)] = []
  1440. for rcpt_to in rcpt_tos:
  1441. msg = email.message_from_bytes(envelope.original_content)
  1442. # Reply case
  1443. # recipient starts with "reply+" or "ra+" (ra=reverse-alias) prefix
  1444. if rcpt_to.startswith("reply+") or rcpt_to.startswith("ra+"):
  1445. LOG.debug("Reply phase %s(%s) -> %s", mail_from, msg["From"], rcpt_to)
  1446. is_delivered, smtp_status = handle_reply(envelope, msg, rcpt_to)
  1447. res.append((is_delivered, smtp_status))
  1448. else: # Forward case
  1449. LOG.debug(
  1450. "Forward phase %s(%s) -> %s",
  1451. mail_from,
  1452. msg["From"],
  1453. rcpt_to,
  1454. )
  1455. for is_delivered, smtp_status in handle_forward(envelope, msg, rcpt_to):
  1456. res.append((is_delivered, smtp_status))
  1457. for (is_success, smtp_status) in res:
  1458. # Consider all deliveries successful if 1 delivery is successful
  1459. if is_success:
  1460. return smtp_status
  1461. # Failed delivery for all, return the first failure
  1462. return res[0][1]
  1463. async def get_spam_score_async(message: Message) -> float:
  1464. LOG.debug("get spam score for %s", message[_MESSAGE_ID])
  1465. sa_input = to_bytes(message)
  1466. # Spamassassin requires to have an ending linebreak
  1467. if not sa_input.endswith(b"\n"):
  1468. LOG.d("add linebreak to spamassassin input")
  1469. sa_input += b"\n"
  1470. try:
  1471. # wait for at max 300s which is the default spamd timeout-child
  1472. response = await asyncio.wait_for(
  1473. aiospamc.check(sa_input, host=SPAMASSASSIN_HOST), timeout=300
  1474. )
  1475. return response.headers["Spam"].score
  1476. except asyncio.TimeoutError:
  1477. LOG.exception("SpamAssassin timeout")
  1478. # return a negative score so the message is always considered as ham
  1479. return -999
  1480. except Exception:
  1481. LOG.exception("SpamAssassin exception")
  1482. return -999
  1483. def get_spam_score(message: Message) -> float:
  1484. LOG.debug("get spam score for %s", message[_MESSAGE_ID])
  1485. sa_input = to_bytes(message)
  1486. # Spamassassin requires to have an ending linebreak
  1487. if not sa_input.endswith(b"\n"):
  1488. LOG.d("add linebreak to spamassassin input")
  1489. sa_input += b"\n"
  1490. try:
  1491. # wait for at max 300s which is the default spamd timeout-child
  1492. sa = SpamAssassin(sa_input, host=SPAMASSASSIN_HOST, timeout=300)
  1493. return sa.get_score()
  1494. except Exception:
  1495. LOG.exception("SpamAssassin exception")
  1496. # return a negative score so the message is always considered as ham
  1497. return -999
  1498. def sl_sendmail(from_addr, to_addr, msg: Message, mail_options, rcpt_options):
  1499. """replace smtp.sendmail"""
  1500. if POSTFIX_SUBMISSION_TLS:
  1501. smtp = SMTP(POSTFIX_SERVER, 587)
  1502. smtp.starttls()
  1503. else:
  1504. smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25)
  1505. # smtp.send_message has UnicodeEncodeErroremail issue
  1506. # encode message raw directly instead
  1507. smtp.sendmail(
  1508. from_addr,
  1509. to_addr,
  1510. msg.as_bytes(),
  1511. mail_options,
  1512. rcpt_options,
  1513. )
  1514. class MailHandler:
  1515. async def handle_DATA(self, server, session, envelope: Envelope):
  1516. try:
  1517. ret = self._handle(envelope)
  1518. return ret
  1519. except Exception:
  1520. LOG.exception(
  1521. "email handling fail %s -> %s",
  1522. envelope.mail_from,
  1523. envelope.rcpt_tos,
  1524. )
  1525. return "421 SL Retry later"
  1526. def _handle(self, envelope: Envelope):
  1527. start = time.time()
  1528. LOG.info(
  1529. "===>> New message, mail from %s, rctp tos %s ",
  1530. envelope.mail_from,
  1531. envelope.rcpt_tos,
  1532. )
  1533. app = new_app()
  1534. with app.app_context():
  1535. ret = handle(envelope)
  1536. LOG.info("takes %s seconds <<===", time.time() - start)
  1537. return ret
  1538. def main(port: int):
  1539. """Use aiosmtpd Controller"""
  1540. controller = Controller(MailHandler(), hostname="0.0.0.0", port=port)
  1541. controller.start()
  1542. LOG.d("Start mail controller %s %s", controller.hostname, controller.port)
  1543. if LOAD_PGP_EMAIL_HANDLER:
  1544. LOG.warning("LOAD PGP keys")
  1545. app = create_app()
  1546. with app.app_context():
  1547. load_pgp_public_keys()
  1548. while True:
  1549. time.sleep(2)
  1550. def asyncio_main(port: int):
  1551. """
  1552. Main entrypoint using asyncio directly without passing by aiosmtpd Controller
  1553. """
  1554. if LOAD_PGP_EMAIL_HANDLER:
  1555. LOG.warning("LOAD PGP keys")
  1556. app = create_app()
  1557. with app.app_context():
  1558. load_pgp_public_keys()
  1559. loop = asyncio.new_event_loop()
  1560. asyncio.set_event_loop(loop)
  1561. lock = asyncio.Lock()
  1562. handler = MailHandler(lock)
  1563. def factory():
  1564. return aiosmtpd.smtp.SMTP(handler, enable_SMTPUTF8=True)
  1565. server = loop.run_until_complete(
  1566. loop.create_server(factory, host="0.0.0.0", port=port)
  1567. )
  1568. try:
  1569. loop.run_forever()
  1570. except KeyboardInterrupt:
  1571. pass
  1572. # Close the server
  1573. LOG.info("Close SMTP server")
  1574. server.close()
  1575. loop.run_until_complete(server.wait_closed())
  1576. loop.close()
  1577. if __name__ == "__main__":
  1578. parser = argparse.ArgumentParser()
  1579. parser.add_argument(
  1580. "-p", "--port", help="SMTP port to listen for", type=int, default=20381
  1581. )
  1582. args = parser.parse_args()
  1583. LOG.info("Listen for port %s", args.port)
  1584. main(port=args.port)