github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/libkb/saferdllloading_windows.go (about)

     1  // Copyright 2016 Keybase, Inc. All rights reserved. Use of
     2  // this source code is governed by the included BSD license.
     3  
     4  package libkb
     5  
     6  import (
     7  	"errors"
     8  	"syscall"
     9  	"unsafe"
    10  )
    11  
    12  const loadLibrarySearchSystem32 = 0x800
    13  
    14  // SaferDLLLoading sets DLL load path to be safer.
    15  func SaferDLLLoading() error {
    16  	kernel32, err := syscall.LoadDLL("kernel32.dll")
    17  	if err != nil {
    18  		return err
    19  	}
    20  
    21  	procSetDllDirectoryW, err := kernel32.FindProc("SetDllDirectoryW")
    22  	if err != nil {
    23  		return err
    24  	}
    25  	var zero uint16
    26  	r1, _, e1 := syscall.Syscall(procSetDllDirectoryW.Addr(), 1,
    27  		uintptr(unsafe.Pointer(&zero)), 0, 0)
    28  
    29  	procSetDefaultDllDirectories, err := kernel32.FindProc("SetDefaultDllDirectories")
    30  	if err == nil && procSetDefaultDllDirectories.Addr() != 0 {
    31  		r1, _, e1 = syscall.Syscall(procSetDefaultDllDirectories.Addr(), 1,
    32  			loadLibrarySearchSystem32, 0, 0)
    33  		if r1 == 0 {
    34  			return e1
    35  		}
    36  	} else {
    37  		return errors.New("SetDefaultDllDirectories not found - please install KB2533623 for safer DLL loading")
    38  	}
    39  
    40  	return nil
    41  }