Skip to content

Commit

Permalink
Merge pull request #177 from k0sproject/ssh-header-windows-detect
Browse files Browse the repository at this point in the history
Detect windows SSH from server header
  • Loading branch information
kke authored Mar 11, 2024
2 parents 68b3cbb + ccf5962 commit eb09155
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 12 deletions.
30 changes: 18 additions & 12 deletions protocol/ssh/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,10 @@ func (c *Connection) Disconnect() {
c.client.Close()
}

func boolptr(b bool) *bool {
return &b
}

// IsWindows is true when the host is running windows.
func (c *Connection) IsWindows() bool {
if c.isWindows != nil {
Expand All @@ -241,21 +245,23 @@ func (c *Connection) IsWindows() bool {
return false
}

var isWin bool
if strings.Contains(string(c.client.ServerVersion()), "Windows") {
isWin = true
c.isWindows = &isWin
return true
}
serverVersion := strings.ToLower(string(c.client.ServerVersion()))
log.Trace(context.Background(), "checking if host is windows", "server_version", serverVersion)

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
switch {
case strings.Contains(serverVersion, "windows"):
c.isWindows = boolptr(true)
case isKnownPosix(serverVersion):
c.isWindows = boolptr(false)
default:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

isWinProc, err := c.StartProcess(ctx, "cmd.exe /c exit 0", nil, nil, nil)
isWin = err == nil && isWinProc.Wait() == nil
isWinProc, err := c.StartProcess(ctx, "ver.exe", nil, nil, nil)
c.isWindows = boolptr(err == nil && isWinProc.Wait() == nil)
}

c.isWindows = &isWin
log.Trace(context.Background(), fmt.Sprintf("host is windows: %t", *c.isWindows), log.KeyHost, c)
log.Trace(context.Background(), fmt.Sprintf("host is windows: %t", *c.isWindows))

return *c.isWindows
}
Expand Down
45 changes: 45 additions & 0 deletions protocol/ssh/knownposix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package ssh

import "strings"

// A list of known ssh server version substrings that are used to aid in
// identifying if a server is windows or not.

var knownPosix = []string{
"linux",
"darwin",
"bsd",
"unix",
"alpine",
"ubuntu",
"debian",
"suse",
"oracle",
"rhel",
"rocky",
"sles",
"fedora",
"amzn",
"arch",
"centos",
"bodhi",
"elementary",
"gentoo",
"kali",
"mageia",
"manjaro",
"slackware",
"solaris",
"illumos",
"aix",
"dragonfly",
}

func isKnownPosix(s string) bool {
for _, v := range knownPosix {
if strings.Contains(s, v) {
return true
}
}
return false
}

0 comments on commit eb09155

Please sign in to comment.