email_handler.py 41 KB

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