email_handler.py 46 KB

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