email_handler.py 49 KB

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