Skip to content

Commit a241a38

Browse files
bradfitzadg
authored andcommitted
runtime, syscall: only search for Windows DLLs in the System32 directory
Make sure that for any DLL that Go uses itself, we only look for the DLL in the Windows System32 directory, guarding against DLL preloading attacks. (Unless the Windows version is ancient and LoadLibraryEx is unavailable, in which case the user probably has bigger security problems anyway.) This does not change the behavior of syscall.LoadLibrary or NewLazyDLL if the DLL name is something unused by Go itself. This change also intentionally does not add any new API surface. Instead, x/sys is updated with a LoadLibraryEx function and LazyDLL.Flags in: https://golang.org/cl/21388 Updates #14959 Change-Id: I8d29200559cc19edf8dcf41dbdd39a389cd6aeb9 Reviewed-on: https://go-review.googlesource.com/21140 Reviewed-by: Russ Cox <[email protected]> Run-TryBot: Brad Fitzpatrick <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-on: https://go-review.googlesource.com/21639 Run-TryBot: Andrew Gerrand <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent 5b874ee commit a241a38

15 files changed

+271
-31
lines changed

src/cmd/dist/build.go

+1
Original file line numberDiff line numberDiff line change
@@ -861,6 +861,7 @@ var buildorder = []string{
861861
"sort",
862862
"container/heap",
863863
"encoding/base64",
864+
"internal/syscall/windows/sysdll",
864865
"syscall",
865866
"internal/syscall/windows/registry",
866867
"time",

src/go/build/deps_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -128,10 +128,10 @@ var pkgDeps = map[string][]string{
128128
// End of linear dependency definitions.
129129

130130
// Operating system access.
131-
"syscall": {"L0", "unicode/utf16"},
131+
"syscall": {"L0", "internal/race", "internal/syscall/windows/sysdll", "unicode/utf16"},
132132
"internal/syscall/unix": {"L0", "syscall"},
133-
"internal/syscall/windows": {"L0", "syscall"},
134-
"internal/syscall/windows/registry": {"L0", "syscall", "unicode/utf16"},
133+
"internal/syscall/windows": {"L0", "syscall", "internal/syscall/windows/sysdll"},
134+
"internal/syscall/windows/registry": {"L0", "syscall", "internal/syscall/windows/sysdll", "unicode/utf16"},
135135
"time": {"L0", "syscall", "internal/syscall/windows/registry"},
136136
"os": {"L1", "os", "syscall", "time", "internal/syscall/windows"},
137137
"path/filepath": {"L2", "os", "syscall"},

src/internal/syscall/windows/registry/syscall.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ package registry
88

99
import "syscall"
1010

11-
//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go syscall.go
11+
//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go -systemdll syscall.go
1212

1313
const (
1414
_REG_OPTION_NON_VOLATILE = 0

src/internal/syscall/windows/registry/zsyscall_windows.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@ package registry
44

55
import "unsafe"
66
import "syscall"
7+
import "internal/syscall/windows/sysdll"
78

89
var _ unsafe.Pointer
910

1011
var (
11-
modadvapi32 = syscall.NewLazyDLL("advapi32.dll")
12-
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
12+
modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
13+
modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
1314

1415
procRegCreateKeyExW = modadvapi32.NewProc("RegCreateKeyExW")
1516
procRegDeleteKeyW = modadvapi32.NewProc("RegDeleteKeyW")

src/internal/syscall/windows/syscall_windows.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ package windows
66

77
import "syscall"
88

9-
//go:generate go run ../../../syscall/mksyscall_windows.go -output zsyscall_windows.go syscall_windows.go
9+
//go:generate go run ../../../syscall/mksyscall_windows.go -output zsyscall_windows.go -systemdll syscall_windows.go
1010

1111
const GAA_FLAG_INCLUDE_PREFIX = 0x00000010
1212

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright 2016 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
// Package sysdll is an internal leaf package that records and reports
6+
// which Windows DLL names are used by Go itself. These DLLs are then
7+
// only loaded from the System32 directory. See Issue 14959.
8+
package sysdll
9+
10+
// IsSystemDLL reports whether the named dll key (a base name, like
11+
// "foo.dll") is a system DLL which should only be loaded from the
12+
// Windows SYSTEM32 directory.
13+
//
14+
// Filenames are case sensitive, but that doesn't matter because
15+
// the case registered with Add is also the same case used with
16+
// LoadDLL later.
17+
//
18+
// It has no associated mutex and should only be mutated serially
19+
// (currently: during init), and not concurrent with DLL loading.
20+
var IsSystemDLL = map[string]bool{}
21+
22+
// Add notes that dll is a system32 DLL which should only be loaded
23+
// from the Windows SYSTEM32 directory. It returns its argument back,
24+
// for ease of use in generated code.
25+
func Add(dll string) string {
26+
IsSystemDLL[dll] = true
27+
return dll
28+
}

src/internal/syscall/windows/zsyscall_windows.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@ package windows
44

55
import "unsafe"
66
import "syscall"
7+
import "internal/syscall/windows/sysdll"
78

89
var _ unsafe.Pointer
910

1011
var (
11-
modiphlpapi = syscall.NewLazyDLL("iphlpapi.dll")
12-
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
12+
modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
13+
modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
1314

1415
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
1516
procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW")

src/runtime/export_windows_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,7 @@
77
package runtime
88

99
var TestingWER = &testingWER
10+
11+
func LoadLibraryExStatus() (useEx, haveEx, haveFlags bool) {
12+
return useLoadLibraryEx, _LoadLibraryExW != nil, _AddDllDirectory != nil
13+
}

src/runtime/os1_windows.go

+29-1
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,11 @@ var (
8888

8989
// Following syscalls are only available on some Windows PCs.
9090
// We will load syscalls, if available, before using them.
91+
_AddDllDirectory,
9192
_AddVectoredContinueHandler,
92-
_GetQueuedCompletionStatusEx stdFunction
93+
_GetQueuedCompletionStatusEx,
94+
_LoadLibraryExW,
95+
_ stdFunction
9396
)
9497

9598
// Call a Windows function with stdcall conventions,
@@ -110,8 +113,10 @@ func loadOptionalSyscalls() {
110113
return stdFunction(unsafe.Pointer(f))
111114
}
112115
if l != 0 {
116+
_AddDllDirectory = findfunc("AddDllDirectory")
113117
_AddVectoredContinueHandler = findfunc("AddVectoredContinueHandler")
114118
_GetQueuedCompletionStatusEx = findfunc("GetQueuedCompletionStatusEx")
119+
_LoadLibraryExW = findfunc("LoadLibraryExW")
115120
}
116121
}
117122

@@ -120,6 +125,11 @@ func getLoadLibrary() uintptr {
120125
return uintptr(unsafe.Pointer(_LoadLibraryW))
121126
}
122127

128+
//go:nosplit
129+
func getLoadLibraryEx() uintptr {
130+
return uintptr(unsafe.Pointer(_LoadLibraryExW))
131+
}
132+
123133
//go:nosplit
124134
func getGetProcAddress() uintptr {
125135
return uintptr(unsafe.Pointer(_GetProcAddress))
@@ -139,13 +149,31 @@ const (
139149
// in sys_windows_386.s and sys_windows_amd64.s
140150
func externalthreadhandler()
141151

152+
// When loading DLLs, we prefer to use LoadLibraryEx with
153+
// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
154+
// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
155+
// flags are not available on some versions of Windows without a
156+
// security patch.
157+
//
158+
// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
159+
// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
160+
// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
161+
// systems that have KB2533623 installed. To determine whether the
162+
// flags are available, use GetProcAddress to get the address of the
163+
// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
164+
// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
165+
// flags can be used with LoadLibraryEx."
166+
var useLoadLibraryEx bool
167+
142168
func osinit() {
143169
asmstdcallAddr = unsafe.Pointer(funcPC(asmstdcall))
144170

145171
setBadSignalMsg()
146172

147173
loadOptionalSyscalls()
148174

175+
useLoadLibraryEx = (_LoadLibraryExW != nil && _AddDllDirectory != nil)
176+
149177
disableWER()
150178

151179
externalthreadhandlerp = funcPC(externalthreadhandler)

src/runtime/syscall_windows.go

+35
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,41 @@ func compileCallback(fn eface, cleanstack bool) (code uintptr) {
8888
return callbackasmAddr(n)
8989
}
9090

91+
const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
92+
93+
//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
94+
//go:nosplit
95+
func syscall_loadsystemlibrary(filename *uint16) (handle, err uintptr) {
96+
c := &getg().m.syscall
97+
98+
if useLoadLibraryEx {
99+
c.fn = getLoadLibraryEx()
100+
c.n = 3
101+
args := struct {
102+
lpFileName *uint16
103+
hFile uintptr // always 0
104+
flags uint32
105+
}{filename, 0, _LOAD_LIBRARY_SEARCH_SYSTEM32}
106+
c.args = uintptr(noescape(unsafe.Pointer(&args)))
107+
} else {
108+
// User is on Windows XP or something ancient.
109+
// The caller wanted to only load the filename DLL
110+
// from the System32 directory but that facility
111+
// doesn't exist, so just load it the normal way. This
112+
// is a potential security risk, but so is Windows XP.
113+
c.fn = getLoadLibrary()
114+
c.n = 1
115+
c.args = uintptr(noescape(unsafe.Pointer(&filename)))
116+
}
117+
118+
cgocall(asmstdcallAddr, unsafe.Pointer(c))
119+
handle = c.r1
120+
if handle == 0 {
121+
err = c.err
122+
}
123+
return
124+
}
125+
91126
//go:linkname syscall_loadlibrary syscall.loadlibrary
92127
//go:nosplit
93128
func syscall_loadlibrary(filename *uint16) (handle, err uintptr) {

src/runtime/syscall_windows_test.go

+93
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ package runtime_test
66

77
import (
88
"fmt"
9+
"internal/syscall/windows/sysdll"
10+
"internal/testenv"
911
"io/ioutil"
1012
"os"
1113
"os/exec"
@@ -640,3 +642,94 @@ uintptr_t cfunc(callback f, uintptr_t n) {
640642
t.Errorf("got %d want %d", got, want)
641643
}
642644
}
645+
646+
// See Issue 14959
647+
func TestDLLPreloadMitigation(t *testing.T) {
648+
if _, err := exec.LookPath("gcc"); err != nil {
649+
t.Skip("skipping test: gcc is missing")
650+
}
651+
652+
dir0, err := os.Getwd()
653+
if err != nil {
654+
t.Fatal(err)
655+
}
656+
defer os.Chdir(dir0)
657+
658+
const src = `
659+
#include <stdint.h>
660+
#include <windows.h>
661+
662+
uintptr_t cfunc() {
663+
SetLastError(123);
664+
}
665+
`
666+
tmpdir, err := ioutil.TempDir("", "TestDLLPreloadMitigation")
667+
if err != nil {
668+
t.Fatal("TempDir failed: ", err)
669+
}
670+
defer os.RemoveAll(tmpdir)
671+
672+
srcname := "nojack.c"
673+
err = ioutil.WriteFile(filepath.Join(tmpdir, srcname), []byte(src), 0)
674+
if err != nil {
675+
t.Fatal(err)
676+
}
677+
name := "nojack.dll"
678+
cmd := exec.Command("gcc", "-shared", "-s", "-Werror", "-o", name, srcname)
679+
cmd.Dir = tmpdir
680+
out, err := cmd.CombinedOutput()
681+
if err != nil {
682+
t.Fatalf("failed to build dll: %v - %v", err, string(out))
683+
}
684+
dllpath := filepath.Join(tmpdir, name)
685+
686+
dll := syscall.MustLoadDLL(dllpath)
687+
dll.MustFindProc("cfunc")
688+
dll.Release()
689+
690+
// Get into the directory with the DLL we'll load by base name
691+
// ("nojack.dll") Think of this as the user double-clicking an
692+
// installer from their Downloads directory where a browser
693+
// silently downloaded some malicious DLLs.
694+
os.Chdir(tmpdir)
695+
696+
// First before we can load a DLL from the current directory,
697+
// loading it only as "nojack.dll", without an absolute path.
698+
delete(sysdll.IsSystemDLL, name) // in case test was run repeatedly
699+
dll, err = syscall.LoadDLL(name)
700+
if err != nil {
701+
t.Fatalf("failed to load %s by base name before sysdll registration: %v", name, err)
702+
}
703+
dll.Release()
704+
705+
// And now verify that if we register it as a system32-only
706+
// DLL, the implicit loading from the current directory no
707+
// longer works.
708+
sysdll.IsSystemDLL[name] = true
709+
dll, err = syscall.LoadDLL(name)
710+
if err == nil {
711+
dll.Release()
712+
if wantLoadLibraryEx() {
713+
t.Fatalf("Bad: insecure load of DLL by base name %q before sysdll registration: %v", name, err)
714+
}
715+
t.Skip("insecure load of DLL, but expected")
716+
}
717+
}
718+
719+
// wantLoadLibraryEx reports whether we expect LoadLibraryEx to work for tests.
720+
func wantLoadLibraryEx() bool {
721+
return testenv.Builder() == "windows-amd64-gce" || testenv.Builder() == "windows-386-gce"
722+
}
723+
724+
func TestLoadLibraryEx(t *testing.T) {
725+
use, have, flags := runtime.LoadLibraryExStatus()
726+
if use {
727+
return // success.
728+
}
729+
if wantLoadLibraryEx() {
730+
t.Fatalf("Expected LoadLibraryEx+flags to be available. (LoadLibraryEx=%v; flags=%v)",
731+
have, flags)
732+
}
733+
t.Skipf("LoadLibraryEx not usable, but not expected. (LoadLibraryEx=%v; flags=%v)",
734+
have, flags)
735+
}

src/syscall/dll_windows.go

+11-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package syscall
66

77
import (
8+
"internal/syscall/windows/sysdll"
89
"sync"
910
"sync/atomic"
1011
"unsafe"
@@ -26,6 +27,7 @@ func Syscall9(trap, nargs, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 u
2627
func Syscall12(trap, nargs, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 uintptr) (r1, r2 uintptr, err Errno)
2728
func Syscall15(trap, nargs, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15 uintptr) (r1, r2 uintptr, err Errno)
2829
func loadlibrary(filename *uint16) (handle uintptr, err Errno)
30+
func loadsystemlibrary(filename *uint16) (handle uintptr, err Errno)
2931
func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err Errno)
3032

3133
// A DLL implements access to a single DLL.
@@ -34,13 +36,19 @@ type DLL struct {
3436
Handle Handle
3537
}
3638

37-
// LoadDLL loads DLL file into memory.
38-
func LoadDLL(name string) (dll *DLL, err error) {
39+
// LoadDLL loads the named DLL file into memory.
40+
func LoadDLL(name string) (*DLL, error) {
3941
namep, err := UTF16PtrFromString(name)
4042
if err != nil {
4143
return nil, err
4244
}
43-
h, e := loadlibrary(namep)
45+
var h uintptr
46+
var e Errno
47+
if sysdll.IsSystemDLL[name] {
48+
h, e = loadsystemlibrary(namep)
49+
} else {
50+
h, e = loadlibrary(namep)
51+
}
4452
if e != 0 {
4553
return nil, &DLLError{
4654
Err: e,

0 commit comments

Comments
 (0)