Primitives for Security Audits: Lessons from Jakarta Mail

Jia Hao Poh (Senior Security Consultant · elttam)

BSides Canberra VIII (2025) · Day 2 · Off-Main Track

Overview

In this insightful talk from BSides Canberra, Jia Hao Poh, a Senior Security Consultant at elttam, delves into the often-overlooked area of auditing library internals for "primitives" – features that, while not bugs themselves, can be misused to introduce security vulnerabilities. Moving beyond common bug patterns, Poh highlights the importance of understanding how libraries process input, especially in hardened targets where easily exploitable flaws are less common. Using Jakarta Mail as a primary case study, he demonstrates how seemingly innocuous design choices, inconsistent behaviors, and expectation mismatches between developers and library parsers can lead to high-impact vulnerabilities, ranging from authentication bypasses to input validation subversion and potential denial-of-service attacks.

Watch on YouTube

Visual summary for Primitives for Security Audits: Lessons from Jakarta Mail by Jia Hao Poh
Visual summary for Primitives for Security Audits: Lessons from Jakarta Mail by Jia Hao Poh

Key moments

  1. 0:00 Introduction: What are security primitives?
  2. 4:00 Primer on encoded email strings and RFC 2047
  3. 6:40 InternetAddress constructor inconsistency: Validation bypass
  4. 8:30 Misinterpreting email addresses via InternetAddress.parse()
  5. 13:00 MyMessage class automatically decodes email headers
  6. 15:30 NewsGroup addresses bypass MyMessage validation
  7. 17:30 Spring Framework's use of Jakarta Mail primitives
  8. 20:00 Bypassing Hibernate Validator's email regex checks

Primitives for Security Audits: Lessons from Jakarta Mail

Speakers: Jia Hao Poh, Senior Security Consultant, elttam

Conference: BSides Canberra

YouTube: https://www.youtube.com/watch?v=BMwfTzxo5_4

Overview

In this insightful talk from BSides Canberra, Jia Hao Poh, a Senior Security Consultant at elttam, delves into the often-overlooked area of auditing library internals for "primitives" – features that, while not bugs themselves, can be misused to introduce security vulnerabilities. Moving beyond common bug patterns, Poh highlights the importance of understanding how libraries process input, especially in hardened targets where easily exploitable flaws are less common. Using Jakarta Mail as a primary case study, he demonstrates how seemingly innocuous design choices, inconsistent behaviors, and expectation mismatches between developers and library parsers can lead to high-impact vulnerabilities, ranging from authentication bypasses to input validation subversion and potential denial-of-service attacks.

The presentation focuses on specific classes within Jakarta Mail, such as InternetAddress and MimeMessage, and extends its analysis to how these components are utilized within frameworks like Spring Framework and Hibernate Validator. Poh's research underscores a critical message for security professionals and developers alike: a deep understanding of underlying library implementations is paramount for identifying subtle yet powerful attack vectors that exploit the nuances of how data, particularly email addresses, is parsed and processed. This talk serves as a compelling argument for thorough source code review and a vigilant approach to integrating third-party libraries, urging practitioners to question how fundamental data structures are handled beneath the surface.

Background

▶ Watch: Introduction: What are security primitives? (0:00)

The journey into Jakarta Mail begins with an understanding of its evolutionary context within the broader Java Enterprise Edition (JEE) ecosystem. Originally known as JavaMail, the library underwent a significant rebranding as part of the transition of Java EE to the Eclipse Foundation. This shift, driven by Oracle's ownership of the "Java" trademark, led to the renaming of Java EE to Jakarta Enterprise Edition (Jakarta EE) in 2019. Jakarta Mail, specifically version 2.1 which Poh's research focused on, is a core component of this platform, residing within a container that comprises various modules and profiles. Its sole known implementation, Angus Mail, is crucial for handling email protocols within Jakarta EE applications.

A foundational element of Poh's investigation revolves around encoded email strings, a feature defined in RFC 2047. This RFC provides a mechanism for email protocols to transport non-ASCII characters, which is particularly relevant in a globalized internet. Encoded strings are typically wrapped in =? and ?= delimiters and consist of three distinct sections: the charset (e.g., UTF-8), the encoding type (e.g., B for Base64 or Q for Quoted-Printable), and the encoded text itself. Poh credits Gareth from PortSwigger for his detailed research on potential misuses of encoded strings, particularly regarding null byte injection, which served as an inspiration for extending this line of inquiry into Jakarta Mail. While Poh did not find null byte issues in Jakarta Mail, the concept of encoded strings and their potential for differential parsing remains a critical area for developers to understand, as many email parsing libraries implicitly support them. This background sets the stage for exploring how Jakarta Mail's handling of these and other email address constructs can create "expectation mismatches" between a developer's assumptions and the library's actual behavior, paving the way for security vulnerabilities.

Key Findings

▶ Watch: InternetAddress constructor inconsistency: Validation bypass (6:40)

Poh's research uncovered several critical "primitives" across Jakarta Mail, Spring Framework, and Hibernate Validator, demonstrating how seemingly benign features or inconsistent implementations can be leveraged for security exploits.

  1. Inconsistent InternetAddress Constructors: The InternetAddress class, central to email address parsing, exhibits inconsistent validation behavior across its constructors. The single-argument constructor (InternetAddress(String address)) rigorously calls the parse() method to validate RFC compliance and throws an exception for invalid input. However, multi-argument constructors (e.g., InternetAddress(String address, String personal)) directly assign the input without calling parse(), effectively bypassing all validation. This discrepancy can easily catch developers off guard, leading to unvalidated email addresses being processed.
  1. Ambiguous InternetAddress.parse() Behavior: The parse() method, despite its 450 lines of "ad hoc mess," shows peculiar behavior when encountering complex email strings, particularly those with angle brackets. For an input like foo <[email protected]>@legit.com, it extracts only the portion within the angle brackets ([email protected]) as the actual email address, ignoring the trailing @legit.com. This creates a differential between the "displayed" or "intended" domain and the actual email recipient, which can be exploited for privilege escalation or identity spoofing.
  1. No Decoding in InternetAddress.getAddress(): While InternetAddress supports encoded strings, the getAddress() method does not perform any decoding on the email address component itself. This means encoding tricks, such as injecting null bytes, are not effective for breaking the parsing logic at this stage.
  1. InternetAddress Group Addresses: The InternetAddress class also supports group addresses (e.g., groupname: addr1, addr2;). These are valid RFC 822 syntax, pass basic validation, and are returned as-is by getAddress(). While not a direct vulnerability, this primitive could be misused in conjunction with other vulnerabilities, such as a dangerous regular expression prone to catastrophic backtracking, leading to a Denial of Service (DoS).
  1. MimeMessage Decoding of Encoded Headers: The MimeMessage class, responsible for representing email envelopes, automatically decodes encoded strings within certain headers like From, Reply-To, and Subject when constructors are used to parse an email envelope. This implicit decoding can subvert input validation logic if an application filters deny-listed words before the decoding occurs, allowing attackers to bypass filters by encoding malicious strings.
  1. MimeMessage.getRecipients() and NewsAddress Weaknesses: When retrieving recipients of RecipientType.NEWSGROUPS, the getRecipients() method accepts and concatenates duplicate News-Groups headers. More critically, the NewsAddress constructor, used to parse these values, performs almost no validation other than stripping whitespace and explicitly does not throw exceptions for malformed input. This lack of validation makes NewsAddress highly permissive, and its impact depends entirely on how an application subsequently uses these unvalidated newsgroup values.
  1. Spring Framework Mail Support Primitives:
  • InternetAddressEditor and SimpleMailMessage: Both classes, when processing email addresses, eventually pass them to InternetAddress constructors or parse() methods. They specifically decode encoded strings found in the personal name section of an email address (e.g., =?UTF-8?B?SmVhbiBNYXJj?= <[email protected]>). This can lead to phishing attacks where a legitimate-looking personal name is displayed, masking a malicious sender.
  • MimeMessageHelper: Its constructor, taking a MimeMessage object and an encoding string, can create encoded strings for non-ASCII personal names. This again highlights the potential for display-based spoofing if the application displays the decoded personal name without proper context or validation.
  1. Hibernate Validator @Email Bypass: The @Email annotation in Hibernate Validator, while useful, allows for custom regular expressions. The default regex, however, can be bypassed. Poh demonstrated that by wrapping "bad characters" in quotes before the @ symbol (e.g., "<bad chars>"@domain.com), the default regex can be satisfied. If an application then naively splits the string by @ and uses the second part as the domain, it could lead to issues.

These findings collectively underscore the complexity of email address parsing and the critical need for developers to understand the intricate behaviors of the libraries they employ.

Technical Deep Dive

▶ Watch: MyMessage class automatically decodes email headers (13:00)

The core of Jia Hao Poh's presentation is a meticulous examination of the internal workings of several Java/Jakarta libraries, highlighting specific methods and constructors that introduce security-relevant "primitives."

Jakarta Mail: InternetAddress Class

The InternetAddress class is fundamental for representing and parsing email addresses. Poh's analysis reveals crucial inconsistencies:

  • Constructors and Validation:
  • InternetAddress(String address): This constructor is the robust one. It invokes the parse() method, which performs extensive validation against RFC 822 standards. If the address string is invalid, this constructor will throw an AddressException, ensuring only RFC-compliant addresses are instantiated.
  • InternetAddress(String address, String personal) and InternetAddress(String address, String personal, String charset): These multi-argument constructors, surprisingly, do not call parse(). Instead, they directly assign the address and personal strings to their respective fields. This bypasses all RFC compliance checks, allowing for the creation of InternetAddress objects with malformed or non-compliant email addresses. This disparity in validation behavior is a significant primitive, as developers might assume consistent validation across all constructors.
  • parse() Method Behavior:
  • Poh describes the parse() method as an "ad hoc mess," spanning approximately 450 lines of code primarily dedicated to positional checks. This complexity itself suggests a higher likelihood of subtle parsing quirks.
  • Angle Bracket Ambiguity: A key finding here is its handling of addresses like "User Name <[email protected]>@malicious.com". The parse() method prioritizes the address within angle brackets, extracting [email protected] as the primary email address. The trailing @malicious.com is effectively ignored for the actual address component. This behavior is critical for scenarios where an application might grant privileges based on the domain (e.g., @fu.com) derived from the last @ symbol, while the email is sent to the address extracted from the angle brackets.
  • Encoded String Handling: The parse() method, and by extension the single-argument constructor, does recognize and process RFC 2047 encoded strings. However, the getAddress() method of the InternetAddress object, which retrieves the parsed email string, does not perform any decoding. This means while the parser understands the encoding, the raw encoded string is returned, preventing direct encoding-based injection attacks at this specific retrieval point.
  • getGroup() Method and Group Addresses:
  • The InternetAddress class also supports group addresses, defined by RFC 822 as groupname: addr1, addr2, ...;. These are distinct from mailing lists.
  • The getGroup() method attempts to return an array of InternetAddress objects if the current address is a group address.
  • Crucially, group addresses are considered valid RFC 822 syntax and will pass the parse() method's validation. When getAddress() is called on an InternetAddress object representing a group, it returns the entire group string as-is. While not directly exploitable, the acceptance of such complex structures as valid email addresses can be a primitive for other attacks, such as triggering Regular Expression Denial of Service (ReDoS) if a downstream application uses a vulnerable regex to process these.

Jakarta Mail: MimeMessage Class

The MimeMessage class represents an entire email, including headers and body.

  • Header Parsing and Decoding:
  • MimeMessage constructors that accept an InputStream (e.g., containing an email envelope) or another MimeMessage object will internally call methods like parseHeader().
  • parseHeader(), in turn, often utilizes the InternetAddress.parse() method for specific headers like From, Reply-To, and Subject.
  • A significant finding is that MimeMessage automatically decodes RFC 2047 encoded strings found within these headers. For example, if a From header contains From: =?UTF-8?B?U29tZSBhdHRhY2tlcg==?= <[email protected]>, the MimeMessage object will internally decode "U29tZSBhdHRhY2tlcg==" to "Some attacker" when accessed. This implicit decoding is a primitive that can bypass input filters that operate on the raw, encoded string before the MimeMessage object is fully constructed.
  • getRecipients() and NewsAddress:
  • When getRecipients() is called with RecipientType.NEWSGROUPS, it retrieves values from the News-Groups header.
  • A critical observation is that the method accepts duplicate News-Groups headers and concatenates their values using a comma delimiter.
  • The concatenated string is then processed by the NewsAddress class. The NewsAddress constructor is extremely permissive: it performs no validation other than stripping whitespace and explicitly states in its comments that it "does not throw an exception if a malformed input is received." This means any arbitrary string, even obviously invalid ones, can be successfully parsed into a NewsAddress object. The security implication here depends entirely on how the application subsequently uses these unvalidated newsgroup addresses.

Spring Framework Mail Support

Poh also investigated how Spring Framework's mail infrastructure (org.springframework.mail.javamail package) interacts with Jakarta Mail, revealing further primitives.

  • InternetAddressEditor: This class is used to prepare InternetAddress objects. Its source code confirms that it simply passes the input string directly to the InternetAddress constructor. As a result, it exhibits the same behavior: it will decode encoded strings in the personal name section but not in the address itself. This can be abused for phishing by crafting a legitimate-looking personal name (e.g., =?UTF-8?B?QXBwbGUgU3VwcG9ydA==?= <[email protected]>).
  • SimpleMailMessage: This class represents a simple email. Its address fields (To, From, Cc, Bcc) eventually route input through InternetAddress.parse(). Consequently, it also decodes encoded strings in the personal name field, leading to similar phishing opportunities where the displayed sender name can be spoofed.
  • MimeMessageHelper: This helper class, often used with MimeMessage, has a constructor that takes a MimeMessage object and a string representing the encoding type. If the personal name section contains non-ASCII characters, this constructor will create encoded strings. Again, the potential for displaying a decoded, spoofed personal name exists, depending on the application's rendering logic.

Hibernate Validator

Finally, Poh touched upon the @Email annotation in Hibernate Validator, a popular validation library.

  • @Email Annotation Bypass: While the default regex for @Email is complex, Poh found a bypass. By wrapping "bad characters" in quotes before the @ symbol (e.g., "<script>alert(1)</script>"@example.com), the default regex can be satisfied. If an application then performs a naive split by @ to extract the domain, it might process the quoted malicious string as part of the local part, potentially leading to further vulnerabilities like XSS if that part is rendered without proper sanitization. The ability to supply a custom regex also means developers can inadvertently introduce their own validation weaknesses.

This deep dive illustrates that security vulnerabilities often arise not from outright bugs, but from the subtle interactions between user input, library features, and the assumptions made by developers about how these features behave.

Demo / Proof of Concept

▶ Watch: NewsGroup addresses bypass MyMessage validation (15:30)

While the talk did not feature a live, interactive demo in the traditional sense, Jia Hao Poh effectively demonstrated the impact of these primitives through illustrative code snippets and example email strings. These examples served as concrete proof-of-concept scenarios for each identified primitive.

For instance, to demonstrate the inconsistent validation in InternetAddress constructors, Poh showed how initializing an InternetAddress object with an invalid string (new InternetAddress("invalid-email")) would throw an exception, whereas new InternetAddress("invalid-email", "Personal Name") would successfully create an object without any validation errors.

The ambiguous parsing of InternetAddress.parse() was illustrated with an email string like foo <[email protected]>@fu.com. Poh explained that the InternetAddress object would extract [email protected] as the actual address, leaving the @fu.com portion effectively ignored for the purpose of the email's destination. This highlighted the potential for an application to grant privileges based on the perceived @fu.com domain while the email is routed to the attacker's controlled address.

The automatic decoding of encoded strings by MimeMessage was showcased using a sample email envelope containing headers like From: =?UTF-8?B?QXR0YWNrZXI=?= <[email protected]>. Poh presented code that parsed this envelope and then confirmed that the From header's personal name was automatically decoded from its Base64 form ("QXR0YWNrZXI=") to its plaintext equivalent ("Attacker"). This illustrated how an input filter applied before MimeMessage processing could be bypassed.

Similarly, the permissive nature of NewsAddress was demonstrated by passing an email with multiple News-Groups headers and showing that MimeMessage would concatenate them and NewsAddress would accept each component without validation.

Finally, the Hibernate Validator @Email bypass was concretized with a specific string example: "<bad chars>"@domain.com. Poh explained that this specific format would pass the default regex, demonstrating how quoting could circumvent validation rules designed to catch malformed email local parts.

These examples, embedded directly within the presentation's code and output, served as clear and reproducible proofs of concept for each primitive, allowing the audience to understand the practical implications of the described behaviors.

Defensive Implications

▶ Watch: Bypassing Hibernate Validator's email regex checks (20:00)

The findings presented by Jia Hao Poh have significant defensive implications for developers, security auditors, and anyone working with email processing in applications. Understanding these primitives is crucial for building more resilient systems.

  1. Validate All User-Supplied Input Thoroughly: The most critical takeaway is that developers should never implicitly trust library defaults or assume consistent behavior across different methods or constructors. Always perform explicit, comprehensive validation on all user-supplied email addresses, regardless of whether a library method "seems" to handle it. This includes checking for RFC compliance, but also considering the contextual use of the email address (e.g., is it for identity, communication, or privilege granting?).
  1. Understand Library Internals and Documentation: Developers must move beyond surface-level usage of libraries. A deep dive into the source code or extensive documentation is necessary, especially for critical components like email parsers. The inconsistency between InternetAddress constructors, for example, highlights how a seemingly minor difference can open a major validation gap. Pay attention to comments like "ad hoc mess" or "does not throw an exception for malformed input."
  1. Beware of Expectation Mismatches: The foo <[email protected]>@legit.com scenario perfectly illustrates an expectation mismatch. Developers might expect the last domain to be authoritative for privilege checks, while the parser extracts the domain from the angle brackets. Implementations for privilege granting or identity verification based on email addresses must specifically extract and validate the intended domain, not just what a generic parser might return. If [email protected] is extracted, then example.com should be used for checks, not legit.com.
  1. Contextual Filtering and Sanitization: When implementing input filters (e.g., denying specific words), consider the possibility of encoded strings. If a library automatically decodes content (like MimeMessage does for headers), filters should be applied after decoding to ensure they catch malicious payloads that were initially encoded. Processing raw, encoded input without considering its eventual decoded form is a common pitfall.
  1. Prudence with Custom Regular Expressions: While custom regex offers flexibility, it also introduces risk. The @Email annotation bypass in Hibernate Validator demonstrates that even complex regex can have blind spots. If custom regex is used for email validation, it must be rigorously tested against a wide range of RFC-compliant and maliciously crafted strings. Relying on well-vetted, established validation libraries and their default, robust regex is often safer than rolling your own.
  1. Mitigate Display-Based Spoofing: The decoding of personal names by Spring Framework's mail classes creates a phishing risk. Applications that display email sender names must ensure that these names are either validated against a trusted source or clearly indicate when they are derived from a potentially untrusted, user-controlled field. Simply displaying the decoded personal name without context can mislead users.
  1. Consider Denial of Service (DoS) Risks: Primitives like group addresses, while not inherently malicious, can be used to craft complex inputs. If an application uses a regex that is vulnerable to catastrophic backtracking, feeding it a group address could trigger a DoS. Developers should use robust regex engines and ensure that parsing logic can handle complex, edge-case inputs without excessive resource consumption.
  1. Regular Security Audits and Source Code Review: The talk strongly advocates for routinely auditing the libraries in use. This isn't just about finding CVEs, but about understanding the "features" or "primitives" that could be repurposed for attack. For critical applications, a manual source code review of how email addresses and other sensitive inputs are handled by underlying libraries is invaluable.

By adopting these defensive postures, organizations can significantly reduce their exposure to vulnerabilities arising from the subtle complexities of email parsing and library interactions.

Key Takeaways

  • Audit Library Internals for "Primitives": Beyond searching for known bug patterns, actively investigate the internal workings of libraries for features or behaviors (primitives) that, while not bugs, can be misused in security contexts.
  • Beware of Inconsistent Library Behavior: Discrepancies in validation or processing across different methods or constructors (e.g., InternetAddress constructors) are significant security risks that can lead to unvalidated input.
  • Understand Email Address Parsing Complexity: Email addresses are complex (RFC 822, RFC 2047). Libraries may handle encoded strings, group addresses, and ambiguous structures in ways that differ from developer expectations, leading to vulnerabilities like spoofing or authentication bypass.
  • Context Matters for Validation: Validation should not be a one-size-fits-all approach. If an email address is used for identity or privilege, ensure the relevant part (e.g., the actual domain for privilege, not a misleading display name) is rigorously validated.
  • Filter and Sanitize Post-Decoding: If a library performs automatic decoding (e.g., MimeMessage for headers), ensure any input filtering or sanitization logic is applied after the decoding process to prevent bypasses.
  • Exercise Caution with Custom Validation Logic: Custom regular expressions or validation rules can introduce new vulnerabilities. Thoroughly test any custom logic against malicious and edge-case inputs, or prefer well-vetted, robust default implementations.

About the Speaker(s)

Jia Hao Poh is a Senior Security Consultant at elttam, a firm that assists clients in securing their assets through various services, including penetration testing. He has a keen interest in web security research, which he pursues in his spare time. This talk at BSides Canberra marked his second time speaking at a security conference, demonstrating his commitment to sharing valuable insights from his research and professional experience with the broader security community.

Reviews

→ Top-rated talks at BSides Canberra VIII (2025)

All talks from BSides Canberra VIII (2025)