Repository navigation
Closed
Labels
area-System.Securityneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsideration
Milestone
Description
Description
When using the Mailkit library for sending emails on containers we are seeing a drastic increase in memory consumed per email. This persists until the container runs out of memory and crashes. This issue was opened on the MailKit repo, but nothing was found in the library causing the issue.
I would expect the GC to free up the memory after the email is sent instead of allowing the consumption to build up until the container crashes.
Example code of sending emails -
public async Task SendEmailAsync(string email, string subject, string htmlMessage) {
var emailMetadata = _tenantMetadata.Value.Email;
var message = new MimeMessage();
//Need a string here and not null otherwise the call is ambiguous
message.To.Add(new MailboxAddress(string.Empty, email));
message.From.Add(new MailboxAddress(emailMetadata.FromName, emailMetadata.FromAddress));
message.Subject = subject;
message.Body = new TextPart(TextFormat.Html) {
Text = htmlMessage
};
var additionalData = new LoggerState() {
{ "From", emailMetadata.FromAddress },
{ "To", email },
{ "Subject", subject },
{ "Smtp location", emailMetadata.Server },
{ "Smtp port", emailMetadata.Port.ToString() }
};
using var emailClient = new SmtpClient();
try {
_logger.LogInformation("Sending email message.", additionalData);
await emailClient.ConnectAsync(emailMetadata.Server, emailMetadata.Port);
emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
await emailClient.SendAsync(message);
_logger.LogInformation("Email successfully sent.", additionalData);
} catch (Exception ex) {
ex.Data.Add("AdditonalData", additionalData);
_logger.LogError(ex, "Email failed to send", additionalData);
throw;
} finally {
await emailClient.DisconnectAsync(true);
}
}Configuration
.NET Core 3.1 3.1.13 runtime x64 on Ubuntu 18.04.5 LTS. Not sure if it's specific to this configuration.
Regression?
Using the legacy SmtpClient functions as expected.
Other information
Not validating the SSL certificate seems to fix this, but is not an option for me.
Metadata
Metadata
Assignees
Labels
area-System.Securityneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsideration
Activity
adamsitnik commentedon Aug 11, 2021
@mwalczyk81 is there any chance that you could capture a GC dump and share it with us? https://github.com/dotnet/diagnostics/blob/main/documentation/dotnet-gcdump-instructions.md
adamsitnik commentedon Aug 11, 2021
I've set the area to Security as from the referenced issue it seems that the leak is specific to SSL certs on Linux.
jstedfast commentedon Aug 11, 2021
@adamsitnik based on the discussion in the MailKit issue, it sounds like it may have something to do with checking for certificate revocation.
In other words, if the
checkCertificateRevocationargument to SslStream.AuthenticateAsClientAsync() istrue, then this issue can be reproduced (at least with some servers?) but if it isfalse, then there is no gain in memory consumption.Apparently different servers result in different amount of leakage. I tested with gmail and saw only a small leak but afaict, it was not coming from MailKit.
mwalczyk81 commentedon Aug 11, 2021
Unfortunately I wasn't able to replicate this on my local machine and don't have access to the containers where the issue happens. I'll reach out again to other team members to see if I can get any help on that.
mwalczyk81 commentedon Oct 11, 2021
Still working with our internal teams to recreate this and get memory dumps
4 remaining items
mwalczyk81 commentedon Oct 26, 2021
@jstedfast do you happen to have any ideas on where these files could go?
jstedfast commentedon Oct 28, 2021
Dropbox or OneDrive? Not sure what the maintainers would prefer
Vandersteen commentedon Jun 23, 2022
Any updates on this issue ?
rzikm commentedon Jun 23, 2022
@Vandersteen, would you be able to provide either a self-contained repro (i.e. sources + dockerfile) or GC dump or full memory dump? We have tried to reproduce the leak in cert validation in the past without success.
Vandersteen commentedon Jun 23, 2022
I believe these are related:
#52577
#55672
jstedfast/MailKit#1105
Someone wrote a repro gist here: https://gist.github.com/MihaZupan/2e207c4c703272961b475e482e96afa3#file-certrevocationmemory-cs-L18-L30
Note: it might be dependent on the domain.
We used mailkit to send emails to
mailtrapon local / dev andmailgunon stg / prdWe only had issues on stg / prd
We now used the
And our memory leaks are gone
rzikm commentedon Jun 24, 2022
I took some time to check this using repro from #55672, I checked using
valgrindand there were no leaks reported that would originate from crypto or certs. I also dumped the malloc info usingmallinfo2in the middle and at the end of the run (I did 10 minutes which seemed sufficient, the Working set was around 720 MB at the end):after 5 minutes:
after 10 minutes:
The main item of importance are the second and third items from the bottom, between the two measurements, the total free space (i.e. memory kept around by the allocator, but not allocated by the application) is growing, while the amount of memory actively being used by the app is more or less steady. This is in line with @bartonjs's suspicion from #52577 (comment).
The problem is that we likely have no way to affect this behavior, even calling
malloc_trimdoes not help, as it would free 72kB at most (see the last item in the report).One thing that still baffles me is how can the total free space grow, since we seem to pretty much just repeatedly allocate and later correctly free the certificate, so to my understanding this should not cause any sort of memory fragmentation which would prevent malloc from releasing more memory.
cc: @wfurt
wfurt commentedon Jun 25, 2022
Can you check counts on various safe handles related CRLs? I've seen similar patterns in the past where small chunks of memory were preventing consolidation and that pushed overall memory use up. You can try to add
GC.Collectto aggressively collect managed objects to see if it makes any difference.rzikm commentedon Jun 27, 2022
Looks like between iterations, there is not really much truly alive concerning certificates. No SafeX509Handles lying around:
DumpHeap listing
So the memory is not being held from managed side (and even explicit GC.Collect has little impact on the observed mallinfo stats). The few
SafeX509StackHandleare the static instances for user/machine cert stores (and in this case are initialized once and not modified for the rest of the program)bartonjs commentedon Jul 29, 2022
Using essentially the same test program as linked above, I see essentially no variation in the total virtual memory size of the process on .NET 6.0 on Ubuntu 18.04 during 3000 serial calls to
revoked.badssl.comin either Online or Offline revocation modes.Two caveats to "essentially no variation":
Since this is consistent with @rzikm's findings, I don't see any other action for us to take.