email_handler.py 51 KB

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