Skip to content

Commit 6718e9e

Browse files
committed
fix(bn) memory leak in bn:to_hex
1 parent e7d0fb6 commit 6718e9e

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

lib/resty/openssl/bn.lua

+4-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ local ffi_str = ffi.string
66
local floor = math.floor
77

88
require "resty.openssl.include.bn"
9+
local crypto_macro = require("resty.openssl.include.crypto")
910
local format_error = require("resty.openssl.err").format_error
1011

1112
local _M = {}
@@ -50,7 +51,9 @@ function _M:to_hex()
5051
if buf == nil then
5152
return nil, format_error("bn:to_hex")
5253
end
53-
return ffi_str(buf), nil
54+
local s = ffi_str(buf)
55+
crypto_macro.OPENSSL_free(buf)
56+
return s, nil
5457
end
5558

5659
function _M.from_binary(s)

lib/resty/openssl/include/crypto.lua

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
local ffi = require "ffi"
2+
local C = ffi.C
3+
4+
local OPENSSL_10 = require("resty.openssl.version").OPENSSL_10
5+
local OPENSSL_11 = require("resty.openssl.version").OPENSSL_11
6+
7+
local OPENSSL_free
8+
if OPENSSL_10 then
9+
ffi.cdef [[
10+
void CRYPTO_free(void *ptr);
11+
]]
12+
OPENSSL_free = C.CRYPTO_free
13+
elseif OPENSSL_11 then
14+
ffi.cdef [[
15+
void CRYPTO_free(void *ptr, const char *file, int line);
16+
]]
17+
OPENSSL_free = function(ptr)
18+
-- file and line is for debuggin only, since we can't know the c file info
19+
-- the macro is expanded, just ignore this
20+
C.CRYPTO_free(ptr, "", 0)
21+
end
22+
end
23+
24+
return {
25+
OPENSSL_free = OPENSSL_free,
26+
}

t/openssl/bn.t

+1
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ bn:to_binary failed
105105
ngx.log(ngx.ERR, err)
106106
return
107107
end
108+
-- valgrind might warn about double free on this test because of the following
108109
require('ffi').C.BN_free(bn.ctx)
109110
local b, err = bn2:to_binary()
110111
if err then

0 commit comments

Comments
 (0)