Skip to content
Permalink
Browse files

Cleanup stale SSH connections if no forwarding requests have been made.

  • Loading branch information...
antoniomika committed Mar 7, 2019
1 parent 5b6e396 commit cc916eb8657358692c3f5d297742e1e602c58f08
Showing with 32 additions and 10 deletions.
  1. +2 −0 README.md
  2. +2 −10 channels.go
  3. +28 −0 main.go
@@ -62,6 +62,8 @@ Usage of ./sish:
Bind ports randomly (OS chooses) (default true)
-sish.bindrange string
Ports that are allowed to be bound (default "0,1024-65535")
-sish.cleanupunbound
Whether or not to cleanup unbound (forwarded) SSH connections (default true)
-sish.debug
Whether or not to print debug information
-sish.domain string
@@ -17,14 +17,6 @@ func handleSession(newChannel ssh.NewChannel, sshConn *SSHConnection, state *Sta
log.Println("Handling session for connection:", connection)
}

cleanUp := func() {
close(sshConn.Close)
close(sshConn.Messages)
sshConn.SSHConn.Close()
state.SSHConnections.Delete(sshConn.SSHConn.RemoteAddr())
log.Println("Closed SSH connection for:", sshConn.SSHConn.RemoteAddr(), "user:", sshConn.SSHConn.User())
}

go func() {
for {
select {
@@ -48,14 +40,14 @@ func handleSession(newChannel ssh.NewChannel, sshConn *SSHConnection, state *Sta
case <-sshConn.Close:
break
default:
cleanUp()
sshConn.CleanUp(state)
}
break
}

if dataRead != 0 {
if data[0] == 3 {
cleanUp()
sshConn.CleanUp(state)
}
}
}
28 main.go
@@ -44,6 +44,7 @@ var (
authPassword = flag.String("sish.password", "S3Cr3tP4$$W0rD", "Password to use for password auth")
authKeysDir = flag.String("sish.keysdir", "pubkeys/", "Directory for public keys for pubkey auth")
bindRange = flag.String("sish.bindrange", "0,1024-65535", "Ports that are allowed to be bound")
cleanupUnbound = flag.Bool("sish.cleanupunbound", true, "Whether or not to cleanup unbound (forwarded) SSH connections")
bindRandom = flag.Bool("sish.bindrandom", true, "Bind ports randomly (OS chooses)")
debug = flag.Bool("sish.debug", false, "Whether or not to print debug information")
)
@@ -136,6 +137,33 @@ func main() {

go handleRequests(reqs, holderConn, state)
go handleChannels(chans, holderConn, state)

if *cleanupUnbound {
go func() {
time.Sleep(1 * time.Second)

count := 0
holderConn.Listeners.Range(func(key, value interface{}) bool {
count++
return true
})

if count == 0 {
holderConn.Messages <- "No forwarding requests sent. Closing connection."
time.Sleep(1 * time.Millisecond)
holderConn.CleanUp(state)
}
}()
}
}()
}
}

// CleanUp closes all allocated resources and cleans them up
func (s *SSHConnection) CleanUp(state *State) {
close(s.Close)
close(s.Messages)
s.SSHConn.Close()
state.SSHConnections.Delete(s.SSHConn.RemoteAddr())
log.Println("Closed SSH connection for:", s.SSHConn.RemoteAddr(), "user:", s.SSHConn.User())
}

0 comments on commit cc916eb

Please sign in to comment.
You can’t perform that action at this time.