email_handler.py 52 KB

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