211 lines
6.8 KiB
Python
211 lines
6.8 KiB
Python
import json
|
|
import re
|
|
import subprocess
|
|
import time
|
|
from dataclasses import dataclass
|
|
|
|
from .domain_names import canonical_domain
|
|
|
|
OPERATION = "inspect_delivery"
|
|
MAX_AGE = 7 * 24 * 60 * 60
|
|
MAX_ENTRIES = 10000
|
|
MAX_RESULTS = 40
|
|
SERVICES = {"qmgr", "smtpd", "smtp", "lmtp", "local", "virtual", "pipe"}
|
|
QUEUE_ID = re.compile(r"\A[A-Za-z0-9]{5,32}\Z")
|
|
LINE = re.compile(r"([A-Za-z0-9]{5,32}): (.*)")
|
|
ADDRESS = re.compile(r"[^<>\s\x00-\x1f]{1,254}")
|
|
SENDER = re.compile(r"^from=<([^<>]*)>,")
|
|
RECIPIENT = re.compile(r"^to=<([^<>]*)>, (?:orig_to=<([^<>]*)>, )?")
|
|
SASL = re.compile(
|
|
r"^client=[^,]+, sasl_method=[A-Za-z0-9_-]+, sasl_username=([^,\s]+)"
|
|
)
|
|
STATUS = re.compile(r"(?:^|, )status=(sent|deferred|bounced|expired)\b")
|
|
DSN = re.compile(r"(?:^|, )dsn=([245]\.\d{1,3}\.\d{1,3}), status=")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class MailDeliveryRequest:
|
|
domain: str
|
|
start: int
|
|
end: int
|
|
sender: str = ""
|
|
recipient: str = ""
|
|
queue_id: str = ""
|
|
|
|
def __post_init__(self):
|
|
object.__setattr__(self, "domain", canonical_domain(self.domain))
|
|
if (
|
|
type(self.start) is not int
|
|
or type(self.end) is not int
|
|
or self.start <= 0
|
|
or not 0 < self.end - self.start <= MAX_AGE
|
|
):
|
|
raise ValueError(
|
|
"Choose a valid time range of at most seven days."
|
|
)
|
|
for query in (self.sender, self.recipient):
|
|
if not isinstance(query, str) or (
|
|
query and not ADDRESS.fullmatch(query)
|
|
):
|
|
raise ValueError("Use an email address for the filter.")
|
|
if not isinstance(self.queue_id, str) or (
|
|
self.queue_id and not QUEUE_ID.fullmatch(self.queue_id)
|
|
):
|
|
raise ValueError("Enter a valid Postfix queue ID.")
|
|
|
|
def manifest(self):
|
|
manifest = {
|
|
"operation": OPERATION,
|
|
"domain": self.domain,
|
|
"start": self.start,
|
|
"end": self.end,
|
|
"sender": self.sender,
|
|
"recipient": self.recipient,
|
|
}
|
|
if self.queue_id:
|
|
manifest["queue_id"] = self.queue_id
|
|
return manifest
|
|
|
|
@classmethod
|
|
def from_manifest(cls, data):
|
|
fields = {"operation", "domain", "start", "end", "sender", "recipient"}
|
|
if (
|
|
not isinstance(data, dict)
|
|
or data.keys() not in (fields, fields | {"queue_id"})
|
|
or data["operation"] != OPERATION
|
|
):
|
|
raise ValueError("Expected a mail delivery request.")
|
|
return cls(
|
|
data["domain"],
|
|
data["start"],
|
|
data["end"],
|
|
data["sender"],
|
|
data["recipient"],
|
|
data.get("queue_id", ""),
|
|
)
|
|
|
|
|
|
def address(value):
|
|
value = value or ""
|
|
return value if ADDRESS.fullmatch(value) else ""
|
|
|
|
|
|
def domain_of(address):
|
|
return address.rpartition("@")[2].lower() if "@" in address else ""
|
|
|
|
|
|
def project_delivery(lines, request):
|
|
envelopes = {}
|
|
authenticated = {}
|
|
records = []
|
|
count = 0
|
|
for encoded in lines:
|
|
count += 1
|
|
entry = json.loads(encoded)
|
|
identity = entry.get("SYSLOG_IDENTIFIER", "")
|
|
service = (
|
|
identity.rpartition("/")[2] if isinstance(identity, str) else ""
|
|
)
|
|
if service not in SERVICES or entry.get("_EXE") != (
|
|
f"/usr/lib/postfix/sbin/{service}"
|
|
):
|
|
continue
|
|
message = entry.get("MESSAGE")
|
|
timestamp = entry.get("__REALTIME_TIMESTAMP")
|
|
if not isinstance(message, str) or not (
|
|
isinstance(timestamp, str)
|
|
and timestamp.isdecimal()
|
|
and len(timestamp) <= 18
|
|
):
|
|
continue
|
|
match = LINE.fullmatch(message)
|
|
if not match:
|
|
continue
|
|
queue_id, text = match.groups()
|
|
if request.queue_id and queue_id != request.queue_id:
|
|
continue
|
|
if service == "qmgr":
|
|
if text == "removed":
|
|
envelopes.pop(queue_id, None)
|
|
authenticated.pop(queue_id, None)
|
|
elif sender := SENDER.match(text):
|
|
envelopes[queue_id] = address(sender[1])
|
|
continue
|
|
if service == "smtpd":
|
|
if login := SASL.match(text):
|
|
authenticated[queue_id] = address(login[1])
|
|
continue
|
|
|
|
addresses = RECIPIENT.match(text)
|
|
if not addresses:
|
|
continue
|
|
status = STATUS.search(text, addresses.end() - 2)
|
|
recipient, original = map(address, addresses.groups())
|
|
sender = envelopes.get(queue_id, "")
|
|
login = authenticated.get(queue_id, "")
|
|
if not status or not recipient:
|
|
continue
|
|
if request.domain != domain_of(original or recipient) and not (
|
|
login
|
|
and login.casefold() == sender.casefold()
|
|
and domain_of(login) == request.domain
|
|
):
|
|
continue
|
|
if request.sender and sender.casefold() != request.sender.casefold():
|
|
continue
|
|
if request.recipient and request.recipient.casefold() not in (
|
|
recipient.casefold(),
|
|
original.casefold(),
|
|
):
|
|
continue
|
|
dsn = DSN.search(text, addresses.end() - 2, status.end())
|
|
records.append(
|
|
{
|
|
"queue_id": queue_id,
|
|
"timestamp": int(timestamp) // 1000000,
|
|
"sender": sender,
|
|
"recipient": recipient,
|
|
"original_recipient": original,
|
|
"status": status[1],
|
|
"dsn": dsn[1] if dsn else "",
|
|
}
|
|
)
|
|
return {
|
|
"events": list(reversed(records[-MAX_RESULTS:])),
|
|
"partial": count > MAX_ENTRIES or len(records) > MAX_RESULTS,
|
|
}
|
|
|
|
|
|
def inspect_delivery(request):
|
|
now = int(time.time())
|
|
if request.end > now + 300 or request.start < now - MAX_AGE - 300:
|
|
raise ValueError("Delivery tracking covers the last seven days.")
|
|
arguments = [
|
|
"/usr/bin/journalctl",
|
|
"--no-pager",
|
|
"--quiet",
|
|
"--output=json",
|
|
"--output-fields=MESSAGE,SYSLOG_IDENTIFIER,_EXE",
|
|
f"--since=@{request.start}",
|
|
f"--until=@{request.end}",
|
|
f"--lines={MAX_ENTRIES + 1}",
|
|
]
|
|
for prefix in ("postfix", "postfix/submission", "postfix/smtps"):
|
|
for service in sorted(SERVICES):
|
|
arguments.append(f"--identifier={prefix}/{service}")
|
|
try:
|
|
result = subprocess.run(
|
|
arguments,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL,
|
|
timeout=20,
|
|
check=True,
|
|
env={"PATH": "/usr/sbin:/usr/bin", "LC_ALL": "C"},
|
|
)
|
|
except (subprocess.SubprocessError, OSError):
|
|
raise ValueError(
|
|
"The receiver could not read the mail journal."
|
|
) from None
|
|
return project_delivery(result.stdout.splitlines(), request)
|