On windows, is it possible to run a single goroutine as a different user?

做~自己de王妃 提交于 2019-12-03 17:26:59

In theory, no, it is not possible because both on Linux and Windows the concept of user's identity only exists for OS-level threads and goroutines are not OS threads—instead, they are very light-weight entities which are mapped to real OS threads by the Go scheduler (a part of the Go runtime built into your executable), and during its lifetime a goroutine might be executed on different OS threads at different times.

But there exist a sort of an "exit hatch" for your situation originally designed to help calling into C code: runtime.LockOSThread(). Once a goroutine calls this function it's stuck to the thread it's currently running on and won't be scheduled to be called on another no matter what until the goroutine exits or calls runtime.UnlockOSThread().

You might use this like this:

go func() {
  runtime.LockOSThread()
  defer runtime.UnlockOSThread()
  impersonate() // acquires and assumes some other credentials
  ...
}

The implementation of that imaginary impersonate() function is out of the scope of this question; you can call any Win32 API function using the syscall package—see the standard Go library for examples.


Note that calling runtime.LockOSThread() in real-world scenarious results in dedicating a whole OS thread to just a single goroutine (while usually a whole lot of them runs on just a single one) so if you plan to spawn a lot of such goroutines locked to OS threads be prepared to deal with increased OS resource usage.

Update: a working example tested on Windows XP Pro SP3 32-bit with Go 1.2.1/i386.

It hard codes the user "foo" identified by the password "foo". To quickly create a user on Windows, do

net user foo * /ADD

and type its password twice when prompted.

Goroutines are green threads and may be mapped around to various operating system threads at will. So your original assumption (that you can do this with a simple syscall.Setuid() on linux) is also probably false. You would need to run in an entirely separate process I think to get the privilege restrictions you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!