email_handler.py 53 KB

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