Skip to content

Commit b95b617

Browse files
committed
fix: guard unix socket cleanup with dev/inode identity check
On exit, only remove the forwarded unix socket if the path still refers to the same file we created. If another process has replaced it in the interim (e.g. a subsequent bind from a different owner), skip the removal to avoid stealing their socket. Recorded via os.Stat after a successful Listen; compared via os.SameFile at cleanup time.
1 parent a2bd7d8 commit b95b617

1 file changed

Lines changed: 15 additions & 2 deletions

File tree

tsshd/forward.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,18 +168,31 @@ func (s *sshUdpServer) handleListenEvent(stream Stream) {
168168
return
169169
}
170170

171+
var createdInfo os.FileInfo
171172
if msg.Net == "unix" {
172173
mode := os.FileMode(0666) &^ os.FileMode(streamLocalBindMask())
173174
if err := os.Chmod(msg.Addr, mode); err != nil {
174175
warning("chmod unix socket [%s] to %#o failed: %v", msg.Addr, mode, err)
175176
}
177+
if info, err := os.Stat(msg.Addr); err == nil {
178+
createdInfo = info
179+
}
176180
}
177181

178182
addOnExitFunc(func() {
179183
_ = listener.Close()
180-
if msg.Net == "unix" {
181-
_ = os.Remove(msg.Addr)
184+
if msg.Net != "unix" || createdInfo == nil {
185+
return
186+
}
187+
current, err := os.Stat(msg.Addr)
188+
if err != nil {
189+
return
190+
}
191+
if !os.SameFile(createdInfo, current) {
192+
debug("unix socket [%s] replaced since creation; skipping unlink", msg.Addr)
193+
return
182194
}
195+
_ = os.Remove(msg.Addr)
183196
})
184197
defer func() { _ = listener.Close() }()
185198

0 commit comments

Comments
 (0)