From 805b4e2dc2afddf7be27e32fe0543e4227b31f74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=8F=A1=E7=8C=AB=E7=8C=AB?= <164346864@qq.com> Date: Mon, 23 Oct 2023 15:11:13 +0800 Subject: [PATCH] fix use after free (#22854) 1. `freeAddrInfo` is called prematurely, the variable `myAddr` is still in use 2. Use defer syntax to ensure that `freeAddrInfo` is also called on exceptions (cherry picked from commit 562a5fb8f9df8985be2543e5581252e449d6ae09) --- lib/pure/nativesockets.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/pure/nativesockets.nim b/lib/pure/nativesockets.nim index e1784491b6200..593bd2d56f397 100644 --- a/lib/pure/nativesockets.nim +++ b/lib/pure/nativesockets.nim @@ -392,6 +392,8 @@ when not useNimNetLite: myAddr: pointer addrLen = 0 family = 0 + + defer: freeAddrInfo(addrInfo) if addrInfo.ai_addr.sa_family.cint == nativeAfInet: family = nativeAfInet @@ -404,8 +406,6 @@ when not useNimNetLite: else: raise newException(IOError, "Unknown socket family in `getHostByAddr()`") - freeAddrInfo(addrInfo) - when useWinVersion: var s = winlean.gethostbyaddr(cast[ptr InAddr](myAddr), addrLen.cuint, cint(family))