Created
August 11, 2021 08:38
-
-
Save iamalsaher/ffc6cf76cce4005e3b81950944bdeab8 to your computer and use it in GitHub Desktop.
Self Injection Output grabbing in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
//This is a modified version of natefinch's npipe where I exposed the handle in PipeConn struct so that I can use it as needed | |
"sepipe/npipe" | |
"bytes" | |
"fmt" | |
"io" | |
"os" | |
"sync" | |
"unsafe" | |
"golang.org/x/sys/windows" | |
) | |
const pipeAddr string = `\\.\pipe\mypipeee` | |
var ( | |
procCreateThread *windows.LazyProc = windows.NewLazySystemDLL("kernel32.dll").NewProc("CreateThread") | |
) | |
func redirectStdout(to windows.Handle) { | |
windows.SetStdHandle(windows.STD_OUTPUT_HANDLE, to) | |
os.Stdout = os.NewFile(uintptr(to), "") | |
} | |
func restoreStdout(f *os.File) { | |
windows.SetStdHandle(windows.STD_OUTPUT_HANDLE, windows.Handle(f.Fd())) | |
os.Stdout = f | |
} | |
func redirectStderr(to windows.Handle) { | |
windows.SetStdHandle(windows.STD_ERROR_HANDLE, to) | |
os.Stderr = os.NewFile(uintptr(to), "") | |
} | |
func restoreStderr(f *os.File) { | |
windows.SetStdHandle(windows.STD_ERROR_HANDLE, windows.Handle(f.Fd())) | |
os.Stderr = f | |
} | |
func redirectIO(to windows.Handle) { | |
redirectStdout(to) | |
redirectStderr(to) | |
} | |
func restoreIO(origStdout, origStderr *os.File) { | |
restoreStdout(origStdout) | |
restoreStderr(origStderr) | |
} | |
func dup(src windows.Handle) (windows.Handle, error) { | |
var ( | |
dupedHandle windows.Handle | |
err error | |
) | |
err = windows.DuplicateHandle(windows.CurrentProcess(), src, windows.CurrentProcess(), &dupedHandle, 0, false, windows.DUPLICATE_SAME_ACCESS) | |
return dupedHandle, err | |
} | |
func hello() { | |
fmt.Println("Hello world from stdout") | |
println("Hello world from stderr") | |
} | |
func makeCallback(f func()) uintptr { | |
return windows.NewCallback(func() uintptr { | |
f() | |
return 0 | |
}) | |
} | |
func createThread(rf func()) (windows.Handle, error) { | |
var threadID uint32 | |
r1, _, err := procCreateThread.Call(0, 0, makeCallback(rf), 0, 0, uintptr(unsafe.Pointer(&threadID))) | |
if r1 == 0 { | |
return 0, fmt.Errorf("error during CreateThread: %v", err) | |
} | |
fmt.Println("Started new thread with ID", threadID) | |
return windows.Handle(r1), nil | |
} | |
func initPipeListener(output *bytes.Buffer, wg *sync.WaitGroup) { | |
lis, err := npipe.Listen(pipeAddr) | |
if err != nil { | |
panic(err) | |
} | |
go func() { | |
for { | |
clConn, err := lis.Accept() | |
if err != nil { | |
println(err) | |
continue | |
} | |
go func() { | |
println(io.Copy(output, clConn)) | |
wg.Done() | |
}() | |
} | |
}() | |
} | |
func main() { | |
saveStdout := os.Stdout | |
output := new(bytes.Buffer) | |
wg := sync.WaitGroup{} | |
initPipeListener(output, &wg) | |
pipeConn, err := npipe.Dial(pipeAddr) | |
if err != nil { | |
panic(err) | |
} | |
redirectStdout(pipeConn.Handle) | |
wg.Add(1) | |
tHandle, err := createThread(hello) | |
if err != nil { | |
panic(err) | |
} | |
windows.WaitForSingleObject(tHandle, windows.INFINITE) | |
pipeConn.Close() | |
wg.Wait() | |
restoreStdout(saveStdout) | |
fmt.Println(`"` + output.String() + `"`) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package npipe | |
import ( | |
"fmt" | |
"io" | |
"net" | |
"sync" | |
"time" | |
"golang.org/x/sys/windows" | |
) | |
const ( | |
// openMode | |
pipe_access_duplex = 0x3 | |
pipe_access_inbound = 0x1 | |
pipe_access_outbound = 0x2 | |
// openMode write flags | |
file_flag_first_pipe_instance = 0x00080000 | |
file_flag_write_through = 0x80000000 | |
file_flag_overlapped = 0x40000000 | |
// pipeMode | |
pipe_type_byte = 0x0 | |
pipe_type_message = 0x4 | |
pipe_unlimited_instances = 255 | |
nmpwait_wait_forever = 0xFFFFFFFF | |
// the two not-an-errors below occur if a client connects to the pipe between | |
// the server's CreateNamedPipe and ConnectNamedPipe calls. | |
error_no_data windows.Errno = 0xE8 | |
error_pipe_connected windows.Errno = 0x217 | |
error_pipe_busy windows.Errno = 0xE7 | |
error_sem_timeout windows.Errno = 0x79 | |
error_bad_pathname windows.Errno = 0xA1 | |
error_invalid_name windows.Errno = 0x7B | |
error_io_incomplete windows.Errno = 0x3e4 | |
) | |
var _ net.Conn = (*PipeConn)(nil) | |
var _ net.Listener = (*PipeListener)(nil) | |
// ErrClosed is the error returned by PipeListener.Accept when Close is called | |
// on the PipeListener. | |
var ErrClosed = PipeError{"Pipe has been closed.", false} | |
// PipeError is an error related to a call to a pipe | |
type PipeError struct { | |
msg string | |
timeout bool | |
} | |
// Error implements the error interface | |
func (e PipeError) Error() string { | |
return e.msg | |
} | |
// Timeout implements net.AddrError.Timeout() | |
func (e PipeError) Timeout() bool { | |
return e.timeout | |
} | |
// Temporary implements net.AddrError.Temporary() | |
func (e PipeError) Temporary() bool { | |
return false | |
} | |
// Dial connects to a named pipe with the given address. If the specified pipe is not available, | |
// it will wait indefinitely for the pipe to become available. | |
// | |
// The address must be of the form \\.\\pipe\<name> for local pipes and \\<computer>\pipe\<name> | |
// for remote pipes. | |
// | |
// Dial will return a PipeError if you pass in a badly formatted pipe name. | |
// | |
// Examples: | |
// // local pipe | |
// conn, err := Dial(`\\.\pipe\mypipename`) | |
// | |
// // remote pipe | |
// conn, err := Dial(`\\othercomp\pipe\mypipename`) | |
func Dial(address string) (*PipeConn, error) { | |
for { | |
conn, err := dial(address, nmpwait_wait_forever) | |
if err == nil { | |
return conn, nil | |
} | |
if isPipeNotReady(err) { | |
<-time.After(100 * time.Millisecond) | |
continue | |
} | |
return nil, err | |
} | |
} | |
// DialTimeout acts like Dial, but will time out after the duration of timeout | |
func DialTimeout(address string, timeout time.Duration) (*PipeConn, error) { | |
deadline := time.Now().Add(timeout) | |
now := time.Now() | |
for now.Before(deadline) { | |
millis := uint32(deadline.Sub(now) / time.Millisecond) | |
conn, err := dial(address, millis) | |
if err == nil { | |
return conn, nil | |
} | |
if err == error_sem_timeout { | |
// This is WaitNamedPipe's timeout error, so we know we're done | |
return nil, PipeError{fmt.Sprintf( | |
"Timed out waiting for pipe '%s' to come available", address), true} | |
} | |
if isPipeNotReady(err) { | |
left := time.Until(deadline) | |
retry := 100 * time.Millisecond | |
if left > retry { | |
<-time.After(retry) | |
} else { | |
<-time.After(left - time.Millisecond) | |
} | |
now = time.Now() | |
continue | |
} | |
return nil, err | |
} | |
return nil, PipeError{fmt.Sprintf( | |
"Timed out waiting for pipe '%s' to come available", address), true} | |
} | |
// isPipeNotReady checks the error to see if it indicates the pipe is not ready | |
func isPipeNotReady(err error) bool { | |
// Pipe Busy means another client just grabbed the open pipe end, | |
// and the server hasn't made a new one yet. | |
// File Not Found means the server hasn't created the pipe yet. | |
// Neither is a fatal error. | |
return err == windows.ERROR_FILE_NOT_FOUND || err == error_pipe_busy | |
} | |
// newOverlapped creates a structure used to track asynchronous | |
// I/O requests that have been issued. | |
func newOverlapped() (*windows.Overlapped, error) { | |
event, err := windows.CreateEvent(nil, 1, 1, nil) | |
if err != nil { | |
return nil, err | |
} | |
return &windows.Overlapped{HEvent: event}, nil | |
} | |
// waitForCompletion waits for an asynchronous I/O request referred to by overlapped to complete. | |
// This function returns the number of bytes transferred by the operation and an error code if | |
// applicable (nil otherwise). | |
func waitForCompletion(handle windows.Handle, overlapped *windows.Overlapped) (uint32, error) { | |
_, err := windows.WaitForSingleObject(overlapped.HEvent, windows.INFINITE) | |
if err != nil { | |
return 0, err | |
} | |
var transferred uint32 | |
err = windows.GetOverlappedResult(handle, overlapped, &transferred, true) | |
return transferred, err | |
} | |
// dial is a helper to initiate a connection to a named pipe that has been started by a server. | |
// The timeout is only enforced if the pipe server has already created the pipe, otherwise | |
// this function will return immediately. | |
func dial(address string, timeout uint32) (*PipeConn, error) { | |
name, err := windows.UTF16PtrFromString(string(address)) | |
if err != nil { | |
return nil, err | |
} | |
// If at least one instance of the pipe has been created, this function | |
// will wait timeout milliseconds for it to become available. | |
// It will return immediately regardless of timeout, if no instances | |
// of the named pipe have been created yet. | |
// If this returns with no error, there is a pipe available. | |
if err := waitNamedPipe(name, timeout); err != nil { | |
if err == error_bad_pathname { | |
// badly formatted pipe name | |
return nil, badAddr(address) | |
} | |
return nil, err | |
} | |
pathp, err := windows.UTF16PtrFromString(address) | |
if err != nil { | |
return nil, err | |
} | |
handle, err := windows.CreateFile(pathp, windows.GENERIC_READ|windows.GENERIC_WRITE, | |
uint32(windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE), nil, windows.OPEN_EXISTING, | |
windows.FILE_FLAG_OVERLAPPED, 0) | |
if err != nil { | |
return nil, err | |
} | |
return &PipeConn{Handle: handle, addr: PipeAddr(address)}, nil | |
} | |
// Listen returns a new PipeListener that will listen on a pipe with the given | |
// address. The address must be of the form \\.\pipe\<name> | |
// | |
// Listen will return a PipeError for an incorrectly formatted pipe name. | |
func Listen(address string) (*PipeListener, error) { | |
handle, err := createPipe(address, true) | |
if err == error_invalid_name { | |
return nil, badAddr(address) | |
} | |
if err != nil { | |
return nil, err | |
} | |
return &PipeListener{ | |
addr: PipeAddr(address), | |
handle: handle, | |
}, nil | |
} | |
// PipeListener is a named pipe listener. Clients should typically | |
// use variables of type net.Listener instead of assuming named pipe. | |
type PipeListener struct { | |
mu sync.Mutex | |
addr PipeAddr | |
handle windows.Handle | |
closed bool | |
// acceptHandle contains the current handle waiting for | |
// an incoming connection or nil. | |
acceptHandle windows.Handle | |
// acceptOverlapped is set before waiting on a connection. | |
// If not waiting, it is nil. | |
acceptOverlapped *windows.Overlapped | |
} | |
// Accept implements the Accept method in the net.Listener interface; it | |
// waits for the next call and returns a generic net.Conn. | |
func (l *PipeListener) Accept() (net.Conn, error) { | |
c, err := l.AcceptPipe() | |
for err == error_no_data { | |
// Ignore clients that connect and immediately disconnect. | |
c, err = l.AcceptPipe() | |
} | |
if err != nil { | |
return nil, err | |
} | |
return c, nil | |
} | |
// AcceptPipe accepts the next incoming call and returns the new connection. | |
// It might return an error if a client connected and immediately cancelled | |
// the connection. | |
func (l *PipeListener) AcceptPipe() (*PipeConn, error) { | |
if l == nil { | |
return nil, windows.ERROR_INVALID_HANDLE | |
} | |
l.mu.Lock() | |
defer l.mu.Unlock() | |
if l.addr == "" || l.closed { | |
return nil, windows.ERROR_INVALID_HANDLE | |
} | |
// the first time we call accept, the handle will have been created by the Listen | |
// call. This is to prevent race conditions where the client thinks the server | |
// isn't listening because it hasn't actually called create yet. After the first time, we'll | |
// have to create a new handle each time | |
handle := l.handle | |
if handle == 0 { | |
var err error | |
handle, err = createPipe(string(l.addr), false) | |
if err != nil { | |
return nil, err | |
} | |
} else { | |
l.handle = 0 | |
} | |
overlapped, err := newOverlapped() | |
if err != nil { | |
return nil, err | |
} | |
defer windows.CloseHandle(overlapped.HEvent) | |
err = windows.ConnectNamedPipe(handle, overlapped) | |
if err == nil || err == error_pipe_connected { | |
return &PipeConn{Handle: handle, addr: l.addr}, nil | |
} | |
if err == error_io_incomplete || err == windows.ERROR_IO_PENDING { | |
l.acceptOverlapped = overlapped | |
l.acceptHandle = handle | |
// unlock here so close can function correctly while we wait (we'll | |
// get relocked via the defer below, before the original defer | |
// unlock happens.) | |
l.mu.Unlock() | |
defer func() { | |
l.mu.Lock() | |
l.acceptOverlapped = nil | |
l.acceptHandle = 0 | |
// unlock is via defer above. | |
}() | |
_, err = waitForCompletion(handle, overlapped) | |
} | |
if err == windows.ERROR_OPERATION_ABORTED { | |
// Return error compatible to net.Listener.Accept() in case the | |
// listener was closed. | |
return nil, ErrClosed | |
} | |
if err != nil { | |
return nil, err | |
} | |
return &PipeConn{Handle: handle, addr: l.addr}, nil | |
} | |
// Close stops listening on the address. | |
// Already Accepted connections are not closed. | |
func (l *PipeListener) Close() error { | |
l.mu.Lock() | |
defer l.mu.Unlock() | |
if l.closed { | |
return nil | |
} | |
l.closed = true | |
if l.handle != 0 { | |
err := disconnectNamedPipe(l.handle) | |
if err != nil { | |
return err | |
} | |
err = windows.CloseHandle(l.handle) | |
if err != nil { | |
return err | |
} | |
l.handle = 0 | |
} | |
if l.acceptOverlapped != nil && l.acceptHandle != 0 { | |
// Cancel the pending IO. This call does not block, so it is safe | |
// to hold onto the mutex above. | |
if err := cancelIoEx(l.acceptHandle, l.acceptOverlapped); err != nil { | |
return err | |
} | |
err := windows.CloseHandle(l.acceptOverlapped.HEvent) | |
if err != nil { | |
return err | |
} | |
l.acceptOverlapped.HEvent = 0 | |
err = windows.CloseHandle(l.acceptHandle) | |
if err != nil { | |
return err | |
} | |
l.acceptHandle = 0 | |
} | |
return nil | |
} | |
// Addr returns the listener's network address, a PipeAddr. | |
func (l *PipeListener) Addr() net.Addr { return l.addr } | |
// PipeConn is the implementation of the net.Conn interface for named pipe connections. | |
type PipeConn struct { | |
Handle windows.Handle | |
addr PipeAddr | |
// these aren't actually used yet | |
readDeadline *time.Time | |
writeDeadline *time.Time | |
} | |
type iodata struct { | |
n uint32 | |
err error | |
} | |
// completeRequest looks at iodata to see if a request is pending. If so, it waits for it to either complete or to | |
// abort due to hitting the specified deadline. Deadline may be set to nil to wait forever. If no request is pending, | |
// the content of iodata is returned. | |
func (c *PipeConn) completeRequest(data iodata, deadline *time.Time, overlapped *windows.Overlapped) (int, error) { | |
if data.err == error_io_incomplete || data.err == windows.ERROR_IO_PENDING { | |
var timer <-chan time.Time | |
if deadline != nil { | |
if timeDiff := time.Until(*deadline); timeDiff > 0 { | |
timer = time.After(timeDiff) | |
} | |
} | |
done := make(chan iodata) | |
go func() { | |
n, err := waitForCompletion(c.Handle, overlapped) | |
done <- iodata{n, err} | |
}() | |
select { | |
case data = <-done: | |
case <-timer: | |
windows.CancelIoEx(c.Handle, overlapped) | |
data = iodata{0, timeout(c.addr.String())} | |
} | |
} | |
// Windows will produce ERROR_BROKEN_PIPE upon closing | |
// a handle on the other end of a connection. Go RPC | |
// expects an io.EOF error in this case. | |
if data.err == windows.ERROR_BROKEN_PIPE { | |
data.err = io.EOF | |
} | |
return int(data.n), data.err | |
} | |
// Read implements the net.Conn Read method. | |
func (c *PipeConn) Read(b []byte) (int, error) { | |
// Use ReadFile() rather than Read() because the latter | |
// contains a workaround that eats ERROR_BROKEN_PIPE. | |
overlapped, err := newOverlapped() | |
if err != nil { | |
return 0, err | |
} | |
defer windows.CloseHandle(overlapped.HEvent) | |
var n uint32 | |
err = windows.ReadFile(c.Handle, b, &n, overlapped) | |
return c.completeRequest(iodata{n, err}, c.readDeadline, overlapped) | |
} | |
// Write implements the net.Conn Write method. | |
func (c *PipeConn) Write(b []byte) (int, error) { | |
overlapped, err := newOverlapped() | |
if err != nil { | |
return 0, err | |
} | |
defer windows.CloseHandle(overlapped.HEvent) | |
var n uint32 | |
err = windows.WriteFile(c.Handle, b, &n, overlapped) | |
return c.completeRequest(iodata{n, err}, c.writeDeadline, overlapped) | |
} | |
// Close closes the connection. | |
func (c *PipeConn) Close() error { | |
return windows.CloseHandle(c.Handle) | |
} | |
// LocalAddr returns the local network address. | |
func (c *PipeConn) LocalAddr() net.Addr { | |
return c.addr | |
} | |
// RemoteAddr returns the remote network address. | |
func (c *PipeConn) RemoteAddr() net.Addr { | |
// not sure what to do here, we don't have remote addr.... | |
return c.addr | |
} | |
// SetDeadline implements the net.Conn SetDeadline method. | |
// Note that timeouts are only supported on Windows Vista/Server 2008 and above | |
func (c *PipeConn) SetDeadline(t time.Time) error { | |
c.SetReadDeadline(t) | |
c.SetWriteDeadline(t) | |
return nil | |
} | |
// SetReadDeadline implements the net.Conn SetReadDeadline method. | |
// Note that timeouts are only supported on Windows Vista/Server 2008 and above | |
func (c *PipeConn) SetReadDeadline(t time.Time) error { | |
c.readDeadline = &t | |
return nil | |
} | |
// SetWriteDeadline implements the net.Conn SetWriteDeadline method. | |
// Note that timeouts are only supported on Windows Vista/Server 2008 and above | |
func (c *PipeConn) SetWriteDeadline(t time.Time) error { | |
c.writeDeadline = &t | |
return nil | |
} | |
// PipeAddr represents the address of a named pipe. | |
type PipeAddr string | |
// Network returns the address's network name, "pipe". | |
func (a PipeAddr) Network() string { return "pipe" } | |
// String returns the address of the pipe | |
func (a PipeAddr) String() string { | |
return string(a) | |
} | |
// createPipe is a helper function to make sure we always create pipes | |
// with the same arguments, since subsequent calls to create pipe need | |
// to use the same arguments as the first one. If first is set, fail | |
// if the pipe already exists. | |
func createPipe(address string, first bool) (windows.Handle, error) { | |
n, err := windows.UTF16PtrFromString(address) | |
if err != nil { | |
return 0, err | |
} | |
mode := uint32(pipe_access_duplex | windows.FILE_FLAG_OVERLAPPED) | |
if first { | |
mode |= file_flag_first_pipe_instance | |
} | |
return windows.CreateNamedPipe(n, | |
mode, | |
pipe_type_byte, | |
pipe_unlimited_instances, | |
512, 512, 0, nil) | |
} | |
func badAddr(addr string) PipeError { | |
return PipeError{fmt.Sprintf("Invalid pipe address '%s'.", addr), false} | |
} | |
func timeout(addr string) PipeError { | |
return PipeError{fmt.Sprintf("Pipe IO timed out waiting for '%s'", addr), true} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package npipe | |
import ( | |
"unsafe" | |
"golang.org/x/sys/windows" | |
) | |
var ( | |
modkernel32 = windows.NewLazyDLL("kernel32.dll") | |
procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe") | |
procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW") | |
procCancelIoEx = modkernel32.NewProc("CancelIoEx") | |
) | |
func waitNamedPipe(name *uint16, timeout uint32) error { | |
r1, _, e1 := procWaitNamedPipeW.Call(uintptr(unsafe.Pointer(name)), uintptr(timeout), 0) | |
if r1 != 0 { | |
return nil | |
} | |
if e1 != nil { | |
return e1 | |
} | |
return windows.ERROR_INVALID_HANDLE | |
} | |
func disconnectNamedPipe(handle windows.Handle) error { | |
r1, _, e1 := procDisconnectNamedPipe.Call(uintptr(handle)) | |
if r1 != 0 { | |
return nil | |
} | |
if e1 != nil { | |
return e1 | |
} | |
return windows.ERROR_INVALID_HANDLE | |
} | |
func cancelIoEx(handle windows.Handle, overlapped *windows.Overlapped) error { | |
r1, _, e1 := procCancelIoEx.Call(uintptr(handle), uintptr(unsafe.Pointer(overlapped))) | |
if r1 != 0 { | |
return nil | |
} | |
if e1 != nil { | |
return e1 | |
} | |
return windows.ERROR_INVALID_HANDLE | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment