Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix memory leak in OpenSSL::SSL::Socket#peer_certificate #13785

Conversation

compumike
Copy link
Contributor

While opening lots of HTTPS connections (from Heii On-Call outbound prober processes for website monitoring / alerting), I discovered a substantial memory leak. This memory leak causes our processes to hit their memory limits and restart several times per day. I traced the leak down to a call to OpenSSL::SSL::Socket#peer_certificate, which we recently started using to inspect SSL certificate expiry dates, so we can warn our users about soon-to-expire certificates.

As per https://www.openssl.org/docs/man3.1/man3/SSL_get1_peer_certificate.html :

The reference count of the X509 object returned by SSL_get1_peer_certificate() is incremented by one, so that it will not be destroyed when the session containing the peer certificate is freed. The X509 object must be explicitly freed using X509_free().

The attached fix ensures that the raw LibCrypto::X509 certificate is freed with LibCrypto.x509_free after it is LibCrypto.x509_dup'd into a new OpenSSL::X509::Certificate instance within the OpenSSL::X509::Certificate constructor.

Running with this change monkeypatched does fix our memory leak. 😄

src/openssl/ssl/socket.cr Outdated Show resolved Hide resolved
Co-authored-by: Sijawusz Pur Rahnama <sija@sija.pl>
@straight-shoota straight-shoota added this to the 1.10.0 milestone Sep 4, 2023
@straight-shoota straight-shoota merged commit fed02a6 into crystal-lang:master Sep 6, 2023
51 of 53 checks passed
Blacksmoke16 pushed a commit to Blacksmoke16/crystal that referenced this pull request Dec 11, 2023
…ang#13785)

Co-authored-by: Sijawusz Pur Rahnama <sija@sija.pl>
@crysbot
Copy link

crysbot commented Mar 29, 2024

This pull request has been mentioned on Crystal Forum. There might be relevant details there:

https://forum.crystal-lang.org/t/how-can-i-get-the-expiration-date-of-an-ssl-certificate-in-crystal/6710/5

This pull request was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants