Skip to content

Commit

Permalink
glog: avoid calling user.Current() on windows (golang#69)
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.

It follows the implementation of the user.Current() implementation in the
standard library.

cl/650142356 (google-internal)
  • Loading branch information
bentekkie authored Jul 9, 2024
1 parent 861d094 commit 9730314
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 9730314

Please sign in to comment.