email_handler.py 55 KB

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