Skip to content

Commit

Permalink
Avoid calling user.Current() on windows
Browse files Browse the repository at this point in the history
Use the current process token to look up the user's name on Windows.

This is more reliable than using the USER or USERNAME environment variables, which are not always set, or might be overridden by the user accidentally or
maliciously.

cl/649607112 (google-internal)
  • Loading branch information
bentekkie committed Jul 9, 2024
1 parent 861d094 commit 125f4ee
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 4 deletions.
6 changes: 2 additions & 4 deletions glog_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import (
"fmt"
"io"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
Expand Down Expand Up @@ -68,9 +67,8 @@ func init() {
host = shortHostname(h)
}

current, err := user.Current()
if err == nil {
userName = current.Username
if u := lookupUser(); u != "" {
userName = u
}
// Sanitize userName since it is used to construct file paths.
userName = strings.Map(func(r rune) rune {
Expand Down
12 changes: 12 additions & 0 deletions glog_file_nonwindows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//go:build !windows

package glog

import "os/user"

func lookupUser() string {
if current, err := user.Current(); err == nil {
return current.Username
}
return ""
}
30 changes: 30 additions & 0 deletions glog_file_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//go:build windows

package glog

import (
"syscall"
)

// This follows the logic in the standard library's user.Current() function, except
// that it leaves out the potentially expensive calls required to look up the user's
// display name in Active Directory.
func lookupUser() string {
token, err := syscall.OpenCurrentProcessToken()
if err != nil {
return ""
}
defer token.Close()
tokenUser, err := token.GetTokenUser()
if err != nil {
return ""
}
username, _, accountType, err := tokenUser.User.Sid.LookupAccount("")
if err != nil {
return ""
}
if accountType != syscall.SidTypeUser {
return ""
}
return username
}

0 comments on commit 125f4ee

Please sign in to comment.